【发布时间】:2015-09-29 20:29:46
【问题描述】:
我有一个控制器,代码如下 sn-p,
...
$scope.selected_contents = [];
$scope.$watch('selected_contents', function (sel_contents) {
console.log(sel_contents, 'selected contents');
}, true);
...
一个指令,
commonDirectives.directive('chkbox', function() {
return {
restrict: 'A',
require: '?ngModel',
scope : {
item : '=item',
selection_pool: '=selectionPool'
},
link: function(scope, elem, attrs, ngModel) {
console.log('selected contents are', scope.selection_pool);
// watch selection_pool
scope.$watch('selection_pool', function (pool) {
console.log(pool, scope.selection_pool, 'pool updated');
if (_.contains(pool, scope.item)) {
elem.prop('checked', true);
}
else {
elem.prop('checked', false);
}
});
// toggle the selection of this component
var toggle_selection = function () {
if(_.indexOf(scope.selection_pool, scope.item) != -1) {
scope.selection_pool = _.without(scope.selection_pool , scope.item);
}
else {
scope.selection_pool.push(scope.item);
}
};
elem.on('click', toggle_selection);
}
};
});
以及使用该指令的模板,
<tr ng-repeat="content in contents">
<td><input type="checkbox" selection_pool="selected_contents" item="content" chkbox></td>
</tr>
问题是,指令中selection_pool 的更改不会反映到控制器中的selected_contents。我错过了什么?
更新 1:
根据@mohamedrias 的建议,我使用scope.$apply 包装了范围内的更改。这样做只会在添加内容时更新控制器中的selected_contents,但在删除内容时不会更新。
...
// toggle the selection of this component
var toggle_selection = function () {
if(_.indexOf(scope.selection_pool, scope.item) != -1) {
scope.$apply(function () {
scope.selection_pool = _.without(scope.selection_pool , scope.item);
});
}
else {
scope.$apply(function () {
scope.selection_pool.push(scope.item);
});
}
};
...
【问题讨论】:
-
您必须在指令的点击处理程序中使用
scope.$apply() -
@mohamedrias 你能解释一下吗?我想知道为什么需要它。
标签: angularjs angularjs-directive angularjs-scope angularjs-ng-repeat