0

我正在做一个 angularjs 项目。并且真的想知道如何访问由 jquery (或其他 javascript 代码)的范围呈现的值。这是我的模板的一部分:

<div class="bars" data-label="Population" data-val="{{town.population}}" data-color="#cccccc">  

因此,我将使用data-val由范围呈现的属性的值。我这样做是这样的:

TownApp.directive('bars', function () {
  return {
    restrict: 'C',
    link: function (scope, elem, attrs) {
         // I tried : this will get value: {{town.population}} as a string itself.
         $(".bar").jqbar({value: $(this).data('val');
         // also tried: this will get undefined
         elem.jqbar({ value: attrs.val});
         // and so on......
    }
  }
}

})

正如我在评论中所描述的,似乎在指令运行时,范围值仍未呈现到页面,因此进一步的代码无法正确读取该值。

所以,我的问题是我该怎么做?非常感谢 !

更新:

添加控制器和工厂代码:

var TownApp=angular.module('TownApp',['ngRoute','ngResource']);

TownApp.factory('Town', function($http) {
    return $http.get('/database.json').then(function(response){
      return response.data;
    })
});

var TownCtrl = TownApp.controller('TownCtrl',function($scope, $routeParams, Town,   $location){
  Town.then(function(response){ 
  $scope.towns = response;

  for (var i = 0; i < response.length; i++) {
     if(response[i].Code === $routeParams.townId){
        var currentTown = response[i];
    }
      $scope.town = currentTown;
  }

  //.......
});

})

4

1 回答 1

1

首先,将您的更改data-val="{{town.population}}"data-val="town.population",我们可以直接从中获取。

然后我们要scope.$eval在指令中使用:

TownApp.directive('bars', function () {
  return {
    restrict: 'C',
    link: function (scope, elem, attrs) {
        // evaluate attribute contents
        elem.jqbar({ value: scope.$eval(attrs.val) });
    }
  }
}

或者,如果您希望能够更新人口值并实时更改条形图(如果 jqbar 支持,我不确定):

TownApp.directive('bars', function () {
  return {
    restrict: 'C',
    link: function (scope, elem, attrs) {
        elem.jqbar({ /* whatever options you want */ });
        scope.$watch(attrs.val, function(val) {
            // I'm not sure of the exact call the update the widget,
            // but it's probably something like this
            elem.jqbar('option', 'value', val);
        });
    }
  }
}

还有第三种方法,使用隔离范围,但如果您在同一元素上有其他指令,这可能会导致问题:

TownApp.directive('bars', function () {
  return {
    restrict: 'C',
    // Make a new isolate scope
    scope: { val: '=' },
    link: function (scope, elem, attrs) {
        elem.jqbar({ value: scope.val });
        // If you want to $watch this value for changes,
        // use scope.$watch('val', function() {...})
    }
  }
}
于 2013-08-21T20:19:39.940 回答