AngularJS嵌套组件双向绑定 - 不起作用

时间:2017-09-05 10:06:52

标签: angularjs angular-components

我是AngularJS的新手,我正面临使用AngularJS组件进行双向绑定的问题。 我有嵌套组件,我试图绑定一些东西并在较低级别更改它(子组件)。

  1. 只能从父级别更改。
  2. $onChanges似乎无法运作,我无法弄清楚原因。
  3. 
    
    var myApp = angular.module('myApp', []);
    myApp.controller('cc', function($scope) {
      $scope.text = 'Initial';
      $scope.data = {
        text: 'Initial'
      };
      $scope.change = function() {
        $scope.data.text = 'Root changed';
        $scope.text = 'Root changed';
      };
    });
    
    myApp.component('parent', {
      transclude: true,
      bindings: {
        data: "<",
        text: "="
      },
      template: '<div><button ng-click="parentController.click()">Parent change</button><div ng-transclude></div></div>',
      controller: function($scope) {
        var self = this;
        this.click = function() {
          self.data.text = 'Parent changed';
          self.text = 'Parent changed';
        };
        this.$onChanges = function() {
        	console.log('$onChanges');
        }
      },
      controllerAs: 'parentController'
    });
    
    myApp.component('child', {
      bindings: {
        data: "<",
        text: "="
      },
      template: '<button ng-click="childController.click()">Child Change</button>',
      controller: function() {
        var self = this;
        this.click = function() {
          self.data.text = 'Child changed';
          self.text = 'Child changed';
        };
      }, 
      controllerAs: 'childController'
    });
    &#13;
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script>
    <div ng-app="myApp" ng-controller="cc">
      <div>
        {{data.text}} text
      </div>
      <div>
        {{text}} text
      </div>
      <button ng-click='change()'>
        Root Change
      </button>
      <parent data="data" text="text">
        <child data="data" text="text"></child>
      </parent>
    </div>
    &#13;
    &#13;
    &#13;

    谢谢!

    JSFiddle demo

1 个答案:

答案 0 :(得分:0)

实际上,对于self.text,您只更新自己的控制器值而不是父范围

日期中的值正在更新,因为对象是通过引用传递的,如果您更改其值,它将被反映到父级,但文本值不会像这样更新

您需要指定现在传递给子的文本属性,因为父控制器也有文本属性,所以如果要传递parents.parents文本属性,请在<child>中执行此操作

<child data="data" text="$parent.$parent.text"></child>

我希望这能解决问题

相关问题