我正在做一个 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;
}
//.......
});
})