在父子指令之间传递参数 [英] Pass argument between parent and child directives

查看:52
本文介绍了在父子指令之间传递参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有用于导航菜单的父指令和用于菜单链接的子指令.像这样:

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

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

在菜单指令中,我使用ng-translucent来添加html. 有什么方法可以将参数从菜单传递给所有菜单链接元素? 例如,如果:

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.

推荐答案

您可以使用require,有关更多信息,请阅读角度指令文档.

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>

这篇关于在父子指令之间传递参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆