[英]AngularJS : How do access parent controller's scope item from the child directive?
[英]How do I access a directive scope from a parent directive/controller?
我有一個模板,它像這樣:
<parent-directive>
<child-directive binding="varFromParent"></child-directive>
<button ng-click="parentDirective.save()"></button>
</parent-directive>
在parentDirective
控制器中執行功能時,是否可以訪問和操作childDirective
的范圍變量,例如,如果我將它們設置為
angular.module('app').directive('parentDirective', function() {
return {
restrict: 'E',
templateUrl: '...',
controllerAs: 'parentDirective',
controller: function($rootScope, $scope) {
//...
this.save = () => {
//Need to manipulate childDirective so that its
//scope.defaultValue == 'NEW DEFAULT'
}
}
}
});
和
angular.module('app').directive('childDirective', function() {
return {
restrict: 'E',
templateUrl: '...',
scope: {
binding: '='
},
controllerAs: 'childDirective',
link: function(scope, elm, attrs) {
scope.defaultValue = 'DEFAULT';
}
}
});
我將如何去做呢? 沒有設置雙向綁定,有沒有辦法做到這一點? 如果可能的話,我想避免<child-directive>
元素上的屬性混亂。
有多種方法可以在您的孩子與父母指令之間建立通信:
雙向綁定 (如您所說)
您的孩子在父母中的登記 。
您可以使用指令require
屬性和鏈接功能controllers
的最后一個參數在其父級中注冊子級。
活動 ,請參閱$scope.on/broadcast
Angular服務 (由於它們是“單子”,因此很容易使用它在指令之間共享數據)
等等
示例2:
angular.module('Example', [])
.directive('parent', [function () {
return {
controller: function (){
// registerChildren etc
}
// ...
};
}])
.directive('children', [function () {
return {
require: ['^^parent', 'children'],
controller: function (){
// ...
}
link: function ($scope, element, attributs, controllers) {
ParentController = controllers[0];
OwnController = controllers[1];
ParentController.registerChildren(OwnController);
// ...
}
// ...
};
}])
在這種情況下,您可能不需要隔離孩子的指令范圍。 定義一個需要在父級作用域上更改的變量,然后子級指令范圍將繼承此值,因此您可以在子級指令中更改它的值,並且可以從父級訪問它。
angular.module('app').directive('parentDirective', function() {
return {
restrict: 'E',
controllerAs: 'parentCtrl',
controller: function($scope) {
$scope.value = 'Value from parent';
this.value = $scope.value
this.save = function() {
this.value = $scope.value;
}
}
}
});
angular.module('app').directive('childDirective', function() {
return {
restrict: 'E',
controllerAs: 'childCtrl',
controller: function($scope) {
$scope.value = 'Value from child';
this.setValue = function() {
$scope.value = 'New value from child';
}
}
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.