Angular directive's link function not being called

北城以北 提交于 2019-12-11 09:47:35

问题


I've got a problem with AngularJS directive link function. It's not beeing called and it doesn't throw any error. Also the template in directive's return is not rendering :( Where should be problem? Thank you for answers!

angular.module('sampleApp.game').directive('gameCanvas', function($injector) {      
    console.log('Directive is working'); // this works,

    function linkFn(scope, ele, attrs) {
        console.log('Link function doesnt working :('); // but this not :(
    };

    return {
        scope: {},
        template: '<div class="blabla"></div>',
        link: linkFn
    }   
});

My html template file

<div class="jumbotron text-center">
    <h1>Play a game!</h1>
    <p>{{ tagline }}</p>   
    <div class="game-canvas"></div>
</div>

回答1:


By default, directives are for Element and Attribute ('EA') only. Define the restrict attribute as 'C'. Best practice is to always define it explicitly.

angular.module('sampleApp.game').directive('gameCanvas', function($injector) {      
console.log('Directive is working'); // this works,

function linkFn(scope, ele, attrs) {
    console.log('Link function doesnt working :('); // but this not :(
};

return {
    scope: {},
    restrict: 'C', //'EA' by default
    template: '<div class="blabla"></div>',
    link: linkFn
}   

});

Documented by Angular here - https://docs.angularjs.org/api/ng/service/$compile#directive-definition-object.



来源:https://stackoverflow.com/questions/29424220/angular-directives-link-function-not-being-called

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!