我有导航菜单的父指令和菜单链接的子指令。像这样:
<menu>
<menu-link />
<menu-link />
</menu>
在菜单指令中,我使用ng-translucent来添加html。 有没有办法将参数从菜单传递到所有菜单链接元素? 例如,如果:
<menu ng-disabled='true'..
我希望所有菜单链接指令从父级获取该值。 还有一件事:每个菜单链接都有自己的属性,因此它需要有自己的范围。
答案 0 :(得分:1)
您可以使用require
,有关详细信息,请阅读angular directive文档。
请参阅示例以获取更多信息:
angular.module('myApp', [])
.controller('MyController', MyController)
.controller('MyDirectiveController', MyDirectiveController)
.directive('myDirective', myDirective)
.directive('childDirective', childDirective)
function MyController($scope) {
}
function MyDirectiveController($scope) {
this.isDisabled = function() {
return $scope.disabled;
};
}
function myDirective() {
return {
restrict: 'E',
transclude: true,
template: '<div>myDirective Disabled: {{ disabled }}<ng-transclude></ng-transclude></div>',
scope: {
disabled: '=?ngDisabled'
},
controller: 'MyDirectiveController'
};
}
function childDirective() {
return {
restrict: 'E',
require: '^^myDirective',
template: '<div>childDirective disabled: {{ disabled }}</div>',
scope: {},
link: function(scope, elem, attrs, myDirectiveCtrl) {
scope.disabled = myDirectiveCtrl.isDisabled();
}
};
}
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="MyController">
<my-directive ng-disabled="true">
<child-directive></child-directive>
<child-directive></child-directive>
</my-directive>
</div>
</div>
&#13;