我需要将父指令(绑定到控制器X)的值传递给子指令,更新它,然后将其一直传递回控制器X updateItem
函数。
这会导致父控制器X接收更新的值,该值会触发新的$digest
循环,并将项目向下传递到链中,依此类推。这会导致无限循环(discussed here)。
我需要更新子指令中的值,那么一旦控制器的$digest
更新,我怎样才能避免重新触发$scope.items
周期?
父控制器X:
$scope.updateItem = function(item) {
$scope.items = item;
};
父指令模板:绑定到父控制器
<div>
<custom-phrases item-to-update="item" update-item="updateItem"></custom-phrases>
</div>
父指令js:
angular
.module('app')
.directive('itemlist',
function($rootScope, $state) {
return {
restrict: 'EA',
templateUrl: 'directives/cms/itemlist/itemlist.tpl.html',
scope: {
},
link: function(scope, element) {
//
},
controller: parentControllerX
};
});
Child指令js:
angular
.module('app')
.directive('customPhrases',
function($rootScope) {
return {
restrict: 'AE',
scope: {
itemToUpdate: '=',
updateItem: '=',
},
templateUrl: 'directives/cms/customPhrases/custom_phrases_directive.tpl.html',
link: function(scope, element) {
scope.itemToUpdate.attr1 += 1;
scope.itemToUpdate.attr2 += 1;
// then pass it back to parent directive
scope.updateItem(scope.itemToUpdate);
...
如果我更改为{{ item }}
:
<div>
<custom-phrases item-to-update="{{ item }}" update-item="updateItem"></custom-phrases>
</div>
并将其传递给child指令,它以字符串形式出现,而不是对象。
编辑2:
如果我只是在子指令中更新items
,就像这样:
scope.items = {
test: 'testing 123'
};
并在子指令中维护双向绑定:
items: '=',
scope.items
永远不会在父指令和控制器级别更新。
答案 0 :(得分:0)
如果您的孩子指示小心更新价值并将其传回父母,那么您不需要双向绑定=
。
您可以使用单向绑定<
scope: {
itemToUpdate: '<', // use one way binding
updateItem: '=',
}
编辑:
我的坏话: 你已经有了双向数据绑定,你不需要从子指令传回来。
scope.updateItem(scope.itemToUpdate);
。 //不需要
它会在那里自动显示。
答案 1 :(得分:0)
我相信您的问题是您在链接功能中调用更新。因此,您正在更新项目,这会导致视图更新,从而导致摘要周期,然后您将永远循环。
你的方法没有任何意义。如果您的父控制器具有将更新您的项目的功能,为什么还要打扰绑定该功能?只需绑定item
并让父控制器处理更新,而不试图来回传递它。无论绑定到属性的是什么,都来自父级,因此只需将其作为参数直接添加到更新函数中的item
。
通过尝试从子控件调用父控制器的更新方法,而不是让双向绑定在item
上执行它的魔术,你过度复杂化了一个简单的绑定解决方案。