2017-09-05 131 views
0

我是AngularJS的新手,我正面臨使用AngularJS組件進行雙向綁定的問題。 我有嵌套的組件,我試圖綁定一些東西,並在較低的級別(子組件)進行更改。AngularJS嵌套組件雙向綁定 - 不起作用

  1. 它只能從父級更改。
  2. $onChanges似乎不工作,我不明白爲什麼。

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() { 
 
    \t 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' 
 
});
<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>

謝謝!

JSFiddle demo

+0

你想改變孩子正確的文本的問題? –

回答

0

實際上self.text你只更新自己的控制器值,而不是父範圍

,因爲對象是按引用傳遞日期的值更新,並在任何你改變它的價值它會反映到父級,但文本值不會像這樣更新

您需要指定現在將哪個文本屬性傳遞給子級,因爲父級控制器也具有文本屬性,所以如果您想要傳遞父級.parents文本屬性在你這裏做這個<child>

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

我希望這將解決

+0

謝謝,它的工作原理! – HadarZH

+0

我的榮幸,歡迎 –