Pass argument between parent and child directives

自古美人都是妖i 提交于 2019-12-02 17:57:29

问题


I have parent directive for navigation menu and child directives for menu links. Something like this:

<menu>
  <menu-link />
  <menu-link />
</menu>

In menu directive I use ng-translucent to be able to add html. Is there any way to pass argument from menu to all menu-link elements? For example, if:

<menu ng-disabled='true'..

I want all menu-link directives to get that value from parent. One more thing: each menu-link have its own attributes, so it needs to have own scope.


回答1:


You can make use of require, for more info read the angular directive doc.

Refer the example for more info:

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();
    }
  };
}
<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>


来源:https://stackoverflow.com/questions/42814530/pass-argument-between-parent-and-child-directives

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!