Я новичок в AngularJS, и у меня возникла проблема с двусторонней привязкой с использованием компонентов AngularJS. У меня есть вложенные компоненты, и я пытаюсь что-то связать и изменить на более низком уровне (дочерний компонент).
- Его можно изменить только с родительского уровня.
$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() {
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>
Спасибо!