在操作Angular指令中的数据(例如,插入或删除数据)时,如何触发$watch
变量,而不是将新对象分配给该变量?
我现在有一个从JSON文件加载的简单数据集。我的Angular控制器可以做到这一点,并定义了一些函数:
App.controller('AppCtrl', function AppCtrl($scope, JsonService) {
// load the initial data model
if (!$scope.data) {
JsonService.getData(function(data) {
$scope.data = data;
$scope.records = data.children.length;
});
} else {
console.log("I have data already... " + $scope.data);
}
// adds a resource to the 'data' object
$scope.add = function() {
$scope.data.children.push({ "name": "!Insert This!" });
};
// removes the resource from the 'data' object
$scope.remove = function(resource) {
console.log("I'm going to remove this!");
console.log(resource);
};
$scope.highlight = function() {
};
});
我有一个正确调用$scope.add
函数的<button>
,并且新对象被正确地插入到$scope.data
集合中。每次我点击“添加”按钮时,我设置的表格都会更新。
<table class="table table-striped table-condensed">
<tbody>
<tr ng-repeat="child in data.children | filter:search | orderBy:'name'">
<td><input type="checkbox"></td>
<td>{{child.name}}</td>
<td><button class="btn btn-small" ng-click="remove(child)" ng-mouseover="highlight()"><i class="icon-remove-sign"></i> remove</button></td>
</tr>
</tbody>
</table>
然而,当这一切发生时,我设置的一个监视$scope.data
的指令并没有被触发。
我用HTML定义我的标记:
<d3-visualization val="data"></d3-visualization>
它与以下指令相关联(为了保证问题的正确性而进行了修剪):
App.directive('d3Visualization', function() {
return {
restrict: 'E',
scope: {
val: '='
},
link: function(scope, element, attrs) {
scope.$watch('val', function(newValue, oldValue) {
if (newValue)
console.log("I see a data change!");
});
}
}
});
我在一开始就收到了"I see a data change!"
消息,但当我点击“添加”按钮后就再也没有收到过。
当我只是在data
对象中添加/删除对象,而不是将整个新的dataset分配给data
对象时,我如何触发$watch
事件?
发布于 2013-06-10 17:55:19
对于使用jqplot绘制数据的指令,我的版本是:
app.directive('lineChart', function() {
$.jqplot.config.enablePlugins = true;
return function(scope, element, attrs) {
scope.$watch(attrs.lineChart, function(newValue, oldValue) {
if (newValue) {
// alert(scope.$eval(attrs.lineChart));
var plot = $.jqplot(element[0].id, scope.$eval(attrs.lineChart), scope.$eval(attrs.options));
}
});
}
});
https://stackoverflow.com/questions/13980896
复制相似问题