Angular 1自定义指令未执行

时间:2017-02-20 04:13:30

标签: javascript angularjs angular-directive

我的指令定义如下:

'use strict;'

angular.module('clientApp')

.directive('afterLast', ['$ocLazyLoad','$timeout',function($ocLazyLoad, $timeout){
    console.log('entered directive');
    return {
        restrict: 'A',
        link: function(scope, elem, attr){
            if (scope.$last === true){
                console.log('entered directive')
                $timeout(function(){
                    $ocLazyLoad.load(['some files'])   
                })
            }
        }
    }
}]);

而且,我使用它作为属性如下:

<div ng-repeat="topicObject in module.topics track by $index" afterLast>

  <div class="ft-section">

    <div ng-repeat="learningPointObject in topicObject.learningPoints track by $index">
        <div class="ft-page">
            <h2 class="module-name" style="text-align: center;">{{module.name | capitalize:true}}</h2>
            <h3 class="topic-name">{{topicObject.name | capitalize:true}}</h3>
            <h4>{{learningPointObject.name | capitalize}}</h4>
            <hr>
         </div>
     </div>

  </div>

</div>  

但是我的指令没有执行。甚至链接功能内外的console.log语句都不起作用。 1.我是否以正确的方式使用指令? 2.如果是,那可能是什么原因导致它不起作用?

2 个答案:

答案 0 :(得分:3)

在HTML中,指令名称必须是kebab-case,而不是camelCase。

 <!-- ERRONEOUS camelCase
 <div ng-repeat="topicObject in module.topics track by $index" afterLast>
 -->

 <!-- USE kebab-case -->
 <div ng-repeat="topicObject in module.topics track by $index" after-last>

有关详细信息,请参阅AngularJS Developer Guide - Directive Normalization

答案 1 :(得分:0)

指令:最后一次观看ng-repeat .. app.directive( 'afterLast',函数(){     返回{         限制:'A',         范围: {},         link:function(scope,element,attrs){             if(attrs.ngRepeat){                 if(范围。$ parent。$ last){                     if(attrs.afterLast!==''){                         if(typeof scope。$ parent。$ parent [attrs.afterLast] ==='function'){                             //执行定义的函数                             。范围$父$ parentattrs.afterLast。                         } else {                             //对于观察者,如果你愿意的话                             范围。$ parent。$ parent [attrs.afterLast] = true;                         }                     }                 }             } else {                 抛出'ngRepeatEndWatch:ngRepeat使用本指令所需的指令';             }         }     } });

上次通话时的函数调用

$ scope.layoutDone = function(){

你想要你的愿望数据

}

html

                             {{module.name |大写:真正}}             {{topicObject.name |大写:真正}}             {{learningPointObject.name |利用}}