为什么在我的自定义指令之后编译ng-class指令

时间:2015-10-27 20:12:05

标签: javascript angularjs angularjs-directive angularjs-ng-repeat

链接到plnkr,例如下面解释:http://plnkr.co/edit/oYvwHnAIvFb4rUqqwsz3?p=preview

嗨,我不明白为什么angular会以这种方式编译我的代码,并需要一些帮助来理解它为什么会这样做。我有一个外部指令,它执行ng-repeat on和array,并为数组中的每个项创建一个新指令。包含这个内部指令的是一个附加了ng-class的div。

我遇到的问题是我希望在调用指令的链接函数之前将ng-class应用于包装div,但事实并非如此。在调用任何包装ng-class函数之前,将编译所有嵌套指令的控制器和链接函数。你可以看到我在上面链接的plnkr中谈论的时间示例(检查控制台以查看打印事物的顺序)。我希望它的打印顺序如下:

adding class to inner directive  1
Inner - Controller undefined
Inner - Link 1
adding class to inner directive  2
Inner - Controller undefined
Inner - Link 2
Inner - Controller undefined
...

任何帮助理解这个/让它按我需要的顺序编译都会很棒。

相关代码: HTML

<div bn-outer>
      <div ng-repeat="a in arr">
        <div  ng-class="classFunction(a)">
          <span bn-inner ng-model="model" ng-init="model=a">

            directive: {{a}}

          </span>  
        </div>

      </div>
    </div>

    // Create an application module for our demo.
    var app = angular.module( "Demo", [] );

    app.directive(
        "bnOuter",
        function() {
            function Controller( $scope ) {
                console.log( "Outer - Controller" );
                $scope.arr = [1,2,3,4,5,6];
                $scope.classFunction = function(int){
                  console.log("adding class to inner directive ", int);
                };
            }
            function link( $scope, element, attributes, controller ) {
                console.log( "Outer - Link" );
            }
            // Return directive configuration.
            return({
                controller: Controller,
                link: link
            });
        }
    );

    app.directive(
        "bnInner",
        function() {
            function Controller( $scope ) {
                console.log( "Inner - Controller", $scope.model );
            }
            function link( $scope, element, attributes, controller ) {
                console.log( "Inner - Link", $scope.model );
            }
            // Return directive configuration.
            return({
                controller: Controller,
                link: link
            });
        }
    );

谢谢!

1 个答案:

答案 0 :(得分:1)