AngularJS directive link function not being called

2019-06-22 07:41发布

问题:

I am trying to use angular-http-auth library with bootstrap modal window. Modals are working fine but I have problems with directives. Here is a jsfiddle link - http://jsfiddle.net/jCUSh/85/ . I am trying to add a directive that will be invoked and that adds listeners. I have simplified the example in jsfiddle, so you won't see http-auth imports. However scope.on('') elements are still left (they don't break the picture anyway).

My question is - why isn't the linking function called? I added elem.addClass('test') as an example. I believe the solution is super simple, just unable to see it.

Also less important question - is it ok to pass scope as a parameter to another scope? I need it to close the modal window.

Thanks

回答1:

Two things are at play here..

One is you must pass the directive through the class attribute and not the ng-class

Secondly, the "C" character you pass to the restrict property is a character with ASCII of 1057 (not our usual ASCII 67 char)

Fixed demo at http://jsfiddle.net/gaby/jCUSh/87/



回答2:

Most of directive errors are displayed in the console, just enable logging:

app.config(function($logProvider){
    $logProvider.debugEnabled(true);
});

Additionally, you may assert if directive was actually loaded:

angular.module('my', [])
    .controller('Controller', [ '$scope', '$injector', 
        function ($scope, $injector) {
           assertDirectives($injector, [ 'dir1', 'dir2']);
         });

function assertDirectives($injector, directives){
    _.each(directives, function(directiveCamelCase){
        if( !$injector.has(directiveCamelCase + 'Directive') ) 
             throw("Directive " + directiveCamelCase + " is not available.")
    });
}
//you may replace underscore's `each` with jquery `each` or regular js loop

Thus you'd have no need to guess why directive is't working.