我正在研究一个现有的Angular应用程序(1.4.3),我试图将其分解为可以更加可重用的组件,并允许更好的升级到Angular 2的路径。
我有一个子组件,它从父级获取输入并显示一个表。在表格中,该输入已插入各种数学公式并显示每个结果数字。我的问题是,当我更新父值时,子组件不反映更新。我认为bindToController
应该是这样做的,这样我就不必密切关注输入。我还注意到,如果我在模板中使用ng-model
vs ng-bind
,事情会变得奇怪。任何人都可以向我解释这里发生了什么,为什么?
答案 0 :(得分:0)
在子指令中未更新值的原因是您在此处将值赋给新变量:
this.item2 = this.item + 25;
然后您的输入绑定到新值item2
。
这是代码的一个分支,我在child指令中添加了第二个输入,它绑定到item
。当您更改父值时,它也会更改。
http://jsbin.com/carolitajo/1/edit?html,js,output
因此,如果您只是直接在子控制器中使用item
属性,则应该全部设置。每次父值更改时,Angular都不会将您的作业重新运行到item2
。
答案 1 :(得分:0)
我最终只是在遇到此评论链后在输入上添加$watch
。它工作得很好。我只是过分担心手表。
http://teropa.info/blog/2015/10/18/refactoring-angular-apps-to-components.html#comment-2446653932
实际上,这种方法效果很好,但仍然感觉更好,因为手表位于与页面控制器相对的组件内部。
如果您使用的是控制器,那么有一个怪癖,我必须在这里发现。 https://toddmotto.com/digging-into-angulars-controller-as-syntax/#ironing-a-quirk
答案 2 :(得分:-2)
怎么样
$scope.$broadcast( "parentCtrlUpdateChild", args );
然后
在你的孩子身上
$scope.$on("parentCtrlUpdateChild", function(event, args) {
...
});
请参阅Todd Motto的解释https://toddmotto.com/all-about-angulars-emit-broadcast-on-publish-subscribing/
看到我为你准备的Bin
http://jsbin.com/zinuqikemo/edit?html,js,output
function parent() {
return {
restrict: 'E',
template: '<div><div><input type="text" ng-model="item"/></div><ng-transclude></ng-transclude></div>',
controllerAs: 'pctrl',
transclude: true,
controller: function($scope) {
$scope.item = 25;
$scope.hola = function() {
$scope.item = $scope.item + 1;
$scope.$broadcast('hola', $scope.item);
};
}
};
}
function child() {
return {
restrict: 'E',
scope: {
item: '='
},
template: '<div><div><input type="text" ng-model="item2"/><div></div></div></div>',
bindToController: true,
controllerAs: 'cctrl',
controller: function($scope) {
$scope.$on('hola', function (event, args) {
$scope.item2 = args + 25;
});
}
};
}
并在您的HTML中添加此
<button ng-click="hola()">HOLA</button>