在AngularJS中从指令中添加指令指令

199

我试图构建一个指令,负责在声明的元素上添加更多的指令。 例如,我想构建一个指令,负责添加datepickerdatepicker-languageng-required="true"

如果我尝试添加这些属性,然后使用$compile,显然会生成无限循环,因此我正在检查是否已经添加了所需的属性:

angular.module('app')
  .directive('superDirective', function ($compile, $injector) {
    return {
      restrict: 'A',
      replace: true,
      link: function compile(scope, element, attrs) {
        if (element.attr('datepicker')) { // check
          return;
        }
        element.attr('datepicker', 'someValue');
        element.attr('datepicker-language', 'en');
        // some more
        $compile(element)(scope);
      }
    };
  });
当然,如果我不对元素进行$compile,那么属性将被设置,但是指令将无法引导。
这种方法正确吗?还是我做错了?有没有更好的方法来实现相同的行为?
UDPATE:鉴于$compile是实现此目的的唯一方法,是否有一种方法可以跳过第一次编译(元素可能包含多个子元素)?也许通过设置terminal:true
UPDATE 2:我尝试将指令放入select元素中,正如预期的那样,编译会运行两次,这意味着有两倍于预期的
7个回答

264

如果您在单个DOM元素上有多个指令,并且它们应用的顺序很重要,您可以使用priority属性来排序它们的应用程序。数字越高,优先级越高。如果不指定优先级,则默认优先级为0。

编辑:经过讨论,这是完整的工作解决方案。关键是要删除属性element.removeAttr("common-things");,以及element.removeAttr("data-common-things");(如果用户在HTML中指定了data-common-things

angular.module('app')
  .directive('commonThings', function ($compile) {
    return {
      restrict: 'A',
      replace: false, 
      terminal: true, //this setting is important, see explanation below
      priority: 1000, //this setting is important, see explanation below
      compile: function compile(element, attrs) {
        element.attr('tooltip', '{{dt()}}');
        element.attr('tooltip-placement', 'bottom');
        element.removeAttr("common-things"); //remove the attribute to avoid indefinite loop
        element.removeAttr("data-common-things"); //also remove the same attribute with data- prefix in case users specify data-common-things in the html

        return {
          pre: function preLink(scope, iElement, iAttrs, controller) {  },
          post: function postLink(scope, iElement, iAttrs, controller) {  
            $compile(iElement)(scope);
          }
        };
      }
    };
  });

可在此链接查看可用的Plunker: http://plnkr.co/edit/Q13bUt?p=preview

或者:

angular.module('app')
  .directive('commonThings', function ($compile) {
    return {
      restrict: 'A',
      replace: false,
      terminal: true,
      priority: 1000,
      link: function link(scope,element, attrs) {
        element.attr('tooltip', '{{dt()}}');
        element.attr('tooltip-placement', 'bottom');
        element.removeAttr("common-things"); //remove the attribute to avoid indefinite loop
        element.removeAttr("data-common-things"); //also remove the same attribute with data- prefix in case users specify data-common-things in the html

        $compile(element)(scope);
      }
    };
  });

演示

为什么我们需要设置terminal: truepriority: 1000(一个高数字)的解释:

当DOM准备就绪时,Angular会遍历DOM以识别所有已注册的指令,并根据priority逐个编译这些指令,如果这些指令在同一元素上。我们将自定义指令的优先级设置为一个较高的数字,以确保它将被首先编译,并使用terminal: true,其他指令将在此指令编译后跳过

当我们的自定义指令被编译时,它将通过添加指令并删除自身来修改元素,并使用$compile服务来编译所有指令(包括那些被跳过的指令)

如果我们不设置terminal:truepriority: 1000,则有可能在我们的自定义指令之前编译一些指令。当我们的自定义指令使用$compile编译元素时,会再次编译已经编译过的指令。这将导致不可预测的行为,特别是如果在我们的自定义指令之前编译的指令已经转换了DOM。

有关优先级和终端的更多信息,请查看如何理解指令的“终端”?

一个还修改模板的指令示例是ng-repeat(priority = 1000),当ng-repeat被编译时,ng-repeat在其他指令应用之前复制模板元素

感谢@Izhaki的评论,这里是ngRepeat源代码的参考:https://github.com/angular/angular.js/blob/master/src/ng/directive/ngRepeat.js


5
当程序不断编译时,它向我抛出了一个栈溢出异常:RangeError: Maximum call stack size exceeded - frapontillo
3
在你的情况下,尝试添加 element.removeAttr("common-datepicker"); 以避免无限循环。 - Khanh TO
4
好的,我已经搞清楚了。你需要设置replace: falseterminal: truepriority: 1000,然后在compile函数中设置所需的属性并移除我们的指令属性。最后,在compile返回的post函数中调用$compile(element)(scope)。该元素将被常规编译,不使用自定义指令,但具有添加的属性。我的目标是不要删除自定义指令,并在一个过程中处理所有内容:这似乎是不可能的。请参考更新后的 plnkr:http://plnkr.co/edit/Q13bUt?p=preview。 - frapontillo
2
请注意,如果您需要使用编译或链接函数的属性对象参数,请知道负责插值属性值的指令优先级为100,而您的指令需要具有比此更低的优先级,否则由于该指令是终端指令,您将只获得属性的字符串值。请参阅(参见此 GitHub pull request和此相关问题)。 - Simen Echholt
2
作为删除“common-things”属性的替代方法,您可以将maxPriority参数传递给编译命令:$compile(element, null, 1000)(scope); - Andreas
显示剩余19条评论

10
您实际上可以使用一个简单的模板标签来处理所有这些问题。请参见http://jsfiddle.net/m4ve9/中的示例。请注意,在超级指令定义中,我实际上不需要编译或链接属性。
在编译过程中,Angular在编译之前提取模板值,因此您可以在那里附加任何进一步的指令,Angular会替您处理它。
如果这是需要保留原始内部内容的超级指令,您可以使用transclude: true并用<ng-transclude></ng-transclude>替换内部内容。
希望这有所帮助,如果有什么不清楚的地方,请让我知道。
Alex

谢谢Alex,这种方法的问题在于我无法对标签做出任何假设。在示例中,它是一个日期选择器,即一个input标签,但我希望它适用于任何元素,例如divselect - frapontillo
1
啊,是的,我错过了那个。在这种情况下,我建议坚持使用div,并确保您的其他指令可以在其上工作。这不是最清晰的答案,但最符合Angular方法论。当引导过程开始编译HTML节点时,它已经收集了节点上所有指令进行编译,因此在那里添加一个新指令不会被原始引导过程注意到。根据您的需求,您可能会发现将所有内容包装在div中并在其中工作会为您提供更多的灵活性,但这也限制了您可以放置元素的位置。 - mrvdot
3
你可以将模板作为函数使用,传入 elementattrs 参数。我花了很长时间才弄明白这个方法,并且我并没有在其他地方看到过它的使用 - 但是它似乎可以正常工作:https://dev59.com/VGIj5IYBdhLWcg3wilvB#20137542 - Patrick

6
这里有一个解决方案,将需要动态添加的指令移至视图中,并添加了一些可选的(基本)条件逻辑。这样可以保持指令干净,没有硬编码的逻辑。
该指令接受一个对象数组,每个对象包含要添加的指令名称和要传递给它的值(如果有)。
直到我想到可能需要根据某些条件(虽然下面的答案仍是牵强附会)仅添加指令时,我才为这样的指令考虑使用情况。我添加了一个可选的if属性,应包含布尔值、表达式或函数(例如,在您的控制器中定义),以确定是否应添加指令。
我还使用attrs.$attr.dynamicDirectives来获取用于添加指令的确切属性声明(例如data-dynamic-directivedynamic-directive),而不是硬编码字符串值进行检查。 Plunker演示

angular.module('plunker', ['ui.bootstrap'])
    .controller('DatepickerDemoCtrl', ['$scope',
        function($scope) {
            $scope.dt = function() {
                return new Date();
            };
            $scope.selects = [1, 2, 3, 4];
            $scope.el = 2;

            // For use with our dynamic-directive
            $scope.selectIsRequired = true;
            $scope.addTooltip = function() {
                return true;
            };
        }
    ])
    .directive('dynamicDirectives', ['$compile',
        function($compile) {
            
             var addDirectiveToElement = function(scope, element, dir) {
                var propName;
                if (dir.if) {
                    propName = Object.keys(dir)[1];
                    var addDirective = scope.$eval(dir.if);
                    if (addDirective) {
                        element.attr(propName, dir[propName]);
                    }
                } else { // No condition, just add directive
                    propName = Object.keys(dir)[0];
                    element.attr(propName, dir[propName]);
                }
            };
            
            var linker = function(scope, element, attrs) {
                var directives = scope.$eval(attrs.dynamicDirectives);
        
                if (!directives || !angular.isArray(directives)) {
                    return $compile(element)(scope);
                }
               
                // Add all directives in the array
                angular.forEach(directives, function(dir){
                    addDirectiveToElement(scope, element, dir);
                });
                
                // Remove attribute used to add this directive
                element.removeAttr(attrs.$attr.dynamicDirectives);
                // Compile element to run other directives
                $compile(element)(scope);
            };
        
            return {
                priority: 1001, // Run before other directives e.g.  ng-repeat
                terminal: true, // Stop other directives running
                link: linker
            };
        }
    ]);
<!doctype html>
<html ng-app="plunker">

<head>
    <script src="//code.angularjs.org/1.2.20/angular.js"></script>
    <script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.6.0.js"></script>
    <script src="example.js"></script>
    <link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css" rel="stylesheet">
</head>

<body>

    <div data-ng-controller="DatepickerDemoCtrl">

        <select data-ng-options="s for s in selects" data-ng-model="el" 
            data-dynamic-directives="[
                { 'if' : 'selectIsRequired', 'ng-required' : '{{selectIsRequired}}' },
                { 'tooltip-placement' : 'bottom' },
                { 'if' : 'addTooltip()', 'tooltip' : '{{ dt() }}' }
            ]">
            <option value=""></option>
        </select>

    </div>
</body>

</html>


在另一个指令模板中使用。它工作得很好,节省了我的时间。只是感谢。 - jcstritt

4

我想分享我的解决方案,因为被接受的那个对我来说并不完全适用。

我需要在元素上添加一个指令,同时还要保留我的指令。

在这个例子中,我在元素上添加了一个简单的ng-style指令。为了防止无限编译循环并允许我保留我的指令,我添加了一个检查来查看我添加的内容是否存在,然后再重新编译元素。

angular.module('some.directive', [])
.directive('someDirective', ['$compile',function($compile){
    return {
        priority: 1001,
        controller: ['$scope', '$element', '$attrs', '$transclude' ,function($scope, $element, $attrs, $transclude) {

            // controller code here

        }],
        compile: function(element, attributes){
            var compile = false;

            //check to see if the target directive was already added
            if(!element.attr('ng-style')){
                //add the target directive
                element.attr('ng-style', "{'width':'200px'}");
                compile = true;
            }
            return {
                pre: function preLink(scope, iElement, iAttrs, controller) {  },
                post: function postLink(scope, iElement, iAttrs, controller) {
                    if(compile){
                        $compile(iElement)(scope);
                    }
                }
            };
        }
    };
}]);

值得注意的是,您不能将其与transclude或模板一起使用,因为编译器会在第二轮尝试重新应用它们。 - spikyjt

1

有一个从1.3.x到1.4.x的变化。

在Angular 1.3.x中,这个是可行的:

var dir: ng.IDirective = {
    restrict: "A",
    require: ["select", "ngModel"],
    compile: compile,
};

function compile(tElement: ng.IAugmentedJQuery, tAttrs, transclude) {
    tElement.append("<option value=''>--- Kein ---</option>");

    return function postLink(scope: DirectiveScope, element: ng.IAugmentedJQuery, attributes: ng.IAttributes) {
        attributes["ngOptions"] = "a.ID as a.Bezeichnung for a in akademischetitel";
        scope.akademischetitel = AkademischerTitel.query();
    }
}

现在在Angular 1.4.x中,我们必须这样做:
var dir: ng.IDirective = {
    restrict: "A",
    compile: compile,
    terminal: true,
    priority: 10,
};

function compile(tElement: ng.IAugmentedJQuery, tAttrs, transclude) {
    tElement.append("<option value=''>--- Kein ---</option>");
    tElement.removeAttr("tq-akademischer-titel-select");
    tElement.attr("ng-options", "a.ID as a.Bezeichnung for a in akademischetitel");

    return function postLink(scope: DirectiveScope, element: ng.IAugmentedJQuery, attributes: ng.IAttributes) {

        $compile(element)(scope);
        scope.akademischetitel = AkademischerTitel.query();
    }
}

(来自被接受的回答:https://dev59.com/8GIk5IYBdhLWcg3wfOOe#19228302,作者是Khanh TO)。


1
尝试将状态存储在元素本身的属性中,例如superDirectiveStatus="true" 例如:
angular.module('app')
  .directive('superDirective', function ($compile, $injector) {
    return {
      restrict: 'A',
      replace: true,
      link: function compile(scope, element, attrs) {
        if (element.attr('datepicker')) { // check
          return;
        }
        var status = element.attr('superDirectiveStatus');
        if( status !== "true" ){
             element.attr('datepicker', 'someValue');
             element.attr('datepicker-language', 'en');
             // some more
             element.attr('superDirectiveStatus','true');
             $compile(element)(scope);

        }

      }
    };
  });

我希望这能帮到你。


谢谢,基本概念保持不变 :). 我正在尝试找出跳过第一次编译的方法。我已经更新了原始问题。 - frapontillo
双重编译会以可怕的方式破坏事物。 - frapontillo

0
一个简单的解决方案是创建并编译一个包装器,然后将原始元素附加到其中。在某些情况下这可行。
类似于以下代码...
link: function(scope, elem, attr){
    var wrapper = angular.element('<div tooltip></div>');
    elem.before(wrapper);
    $compile(wrapper)(scope);
    wrapper.append(elem);
}

这种解决方案的优点在于它通过不重新编译原始元素来保持简单。

如果任何添加的指令“require”原始元素的任何指令或者原始元素具有绝对定位,则此方法将无法工作。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接