[英]$watch'ing for data changes in an Angular directive
在操作內部數據(例如,插入或刪除數據)時,如何在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
對象中添加/刪除對象時,如何才能觸發$watch
事件,而不是將全新的數據集分配給data
對象?
您需要啟用深層對象臟檢查。 默認情況下,angular僅檢查您觀看的頂級變量的引用。
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!");
}, true);
}
}
});
見范圍 。 $ watch函數的第三個參數啟用深度臟檢查,如果它設置為true。
請注意深度臟檢查是昂貴的 。 因此,如果您只需要觀察子數組而不是整個data
變量,則直接觀察變量。
scope.$watch('val.children', function(newValue, oldValue) {}, true);
版本1.2.x引入了$ watchCollection
Shallow監視對象的屬性,並在任何屬性發生更改時觸發(對於數組,這意味着要觀察數組項;對於對象映射,這意味着要查看屬性)
scope.$watchCollection('val.children', function(newValue, oldValue) {});
因為如果要觸發深的是你的數據,你必須通過3TH說法true
的listener.By默認它是false
,它meens你函數將觸發,只有當你的變量將不會改變它的領域 。
我的版本是一個指令,它使用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));
}
});
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.