Javascript 如何从父指令/控制器访问指令范围?
我有一个这样的模板:Javascript 如何从父指令/控制器访问指令范围?,javascript,angularjs,Javascript,Angularjs,我有一个这样的模板: <parent-directive> <child-directive binding="varFromParent"></child-directive> <button ng-click="parentDirective.save()"></button> </parent-directive> 及 我该怎么做呢?有没有办法在不设置双向绑定的情况下实现这一点?如果可能的话,我希望避
<parent-directive>
<child-directive binding="varFromParent"></child-directive>
<button ng-click="parentDirective.save()"></button>
</parent-directive>
及
我该怎么做呢?有没有办法在不设置双向绑定的情况下实现这一点?如果可能的话,我希望避免
元素上的属性混乱 在您的孩子和您的家长之间建立沟通有很多方法:
require
属性和链接函数controllers
的最后一个参数在其父项中注册子项
$scope.on/broadcast
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);
// ...
}
// ...
};
}])
在这种情况下,您可能不需要隔离child的指令范围。定义一个您需要在父级范围内更改的变量,然后子级的指令范围将继承此值,这样您就可以在子级的指令中更改它的值,并且可以从父级访问它
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';
}
}
}
});
这是小提琴
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';
}
}
}
});