AngularJS在父元素更改时更新子组件

AngularJS updating child component when parent element changes

本文关键字:更新 组件 元素 AngularJS      更新时间:2023-09-26

我正在开发一个现有的 Angular 应用程序 (1.4.3),我正在尝试将内容分解为可以更可重用的组件,并允许更好地升级到 Angular 2。

我有一个子组件,它从父组件获取输入并显示一个表。在表中,该输入已插入各种数学公式并显示每个结果数字。我的问题是,当我更新父值时,子组件不会反映更新。我认为bindToController应该做的是这样我就不必在输入上放手表。我还注意到,如果我在模板中使用ng-modelng-bind,事情会变得很奇怪。谁能向我解释一下这里发生了什么,为什么?

下面是一个示例。 http://jsbin.com/yoqenahini/1/edit?html,js,output

子指令中未更新值的原因是您将值分配给此处的新变量:

this.item2 = this.item + 25;

然后您的输入将绑定到新值 item2 .

这是您的代码的一个分支,我在绑定到 item 的子指令中添加了第二个输入。当您更改父值时,它也会更改。

http://jsbin.com/carolitajo/1/edit?html,js,output

因此,如果您只是直接在子控制器中使用 item 属性,您应该已经全部设置好了。Angular 不会在每次父值更改时重新运行您的分配以item2

遇到这个评论链后,我最终只是在输入中添加了一个$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

$scope.$broadcast( "parentCtrlUpdateChild", args );

然后

在你的孩子

$scope.$on("parentCtrlUpdateChild", function(event, args) {
  ...
});

请参阅托德·莫托的解释 https://toddmotto.com/all-about-angulars-emit-broadcast-on-publish-subscribing/

看到我为你准备的这个斌

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>