如果存在,如何要求指令(在另一个指令内)

时间:2015-01-12 09:04:30

标签: javascript angularjs angularjs-directive

假设我们需要创建两种方法来定义指令的配置:

1 - 使用元素属性

<any main-dir main-name="myname" name-id="may-id" main-other-config="other config"></any>

2-需要另一个指令

app.directive("mainDirConfig", function () {
  return {
    controller: function (scope){
      scope.config = {
        name: 'my name',
        id: 'my-id',
        otherConfigs: 'other config'
      }
    }
  }
});


<any main-dir main-dir-config></any>

仅当mainDirConfig存在时,如何在mainDir指令内(作为首选方式)需要mainDirConfig指令,否则使用元素属性作为配置?

更多信息:我想将此配置用于外部模块,我需要将用户配置与模块分开。

1 个答案:

答案 0 :(得分:1)

来自角度文档here

<强>需要

Require another directive and inject its controller as the fourth argument to the linking function. The require takes a string name (or array of strings) of the directive(s) to pass in. If an array is used, the injected argument will be an array in corresponding order. If no such directive can be found, or if the directive does not have a controller, then an error is raised. The name can be prefixed with:

(no prefix) - Locate the required controller on the current element. Throw an error if not found.
? - Attempt to locate the required controller or pass null to the link fn if not found.
^ - Locate the required controller by searching the element and its parents. Throw an error if not found.
^^ - Locate the required controller by searching the element's parents. Throw an error if not found.
?^ - Attempt to locate the required controller by searching the element and its parents or pass null to the link fn if not found.
?^^ - Attempt to locate the required controller by searching the element's parents, or pass null to the link fn if not found.

在指令部分提到它,但只在$ compile部分中完全定义。