【问题标题】:Why is the ng-class directive being compiled after my custom directives为什么在我的自定义指令之后编译 ng-class 指令
【发布时间】:2016-01-27 10:22:07
【问题描述】:

plnkr 的链接示例如下:http://plnkr.co/edit/oYvwHnAIvFb4rUqqwsz3?p=preview

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

我遇到的问题是我希望在调用指令的链接函数之前将 ng-class 应用于包装 div,但事实并非如此。所有嵌套指令的控制器和链接函数在调用任何包装 ng 类函数之前编译。您可以在我上面链接的 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
            });
        }
    );

谢谢!

【问题讨论】:

  • 能否请您在问题中也发布相关代码。
  • 调用 ngclass 表达式不同于编译 ng-class 指令。你不是在比较苹果和苹果。 ng-class 表达式在 first watch execution 期间进行评估,这发生在编译指令后的摘要循环期间。如果您将 console.log 放在 ng-class 链接函数中,您将能够注意到一致性。
  • I want the ng-class to be applied to the wrapping div before the directive's link function is called --> 为什么编译指令需要如此紧密的耦合?相反,如果您希望在编译、绑定和渲染所有指令之后在该指令中执行操作,您可以通过将其推入异步队列来使用 $timeout 推迟它。它将确保在编译指令后运行的第一个摘要循环之后运行该段代码。
  • 这是有道理的,我现在明白这个问题了。我可能不得不重写我的一些指令来做一些解耦。谢谢

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


【解决方案1】:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-06
    • 2017-07-29
    • 2012-12-14
    • 1970-01-01
    • 1970-01-01
    • 2015-05-05
    • 1970-01-01
    • 2018-06-13
    相关资源
    最近更新 更多