【问题标题】:Angular directive's link function not being calledAngular 指令的链接函数没有被调用
【发布时间】:2015-04-02 23:38:27
【问题描述】:

我遇到了 AngularJS 指令链接功能的问题。它没有被调用,也不会引发任何错误。指令返回中的模板也没有渲染:(应该是哪里出了问题?谢谢你的回答!

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
    }   
});

我的html模板文件

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

【问题讨论】:

  • 尝试添加restrict: "C" 或您想要的任何其他限制。
  • 不错!有用!但为什么? :D 为什么它以前不起作用?

标签: javascript angularjs angularjs-directive


【解决方案1】:

默认情况下,指令仅适用于元素和属性 ('EA')。将限制属性定义为“C”。最佳做法是始终明确定义它。

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
}   

});

由 Angular 记录在这里 - https://docs.angularjs.org/api/ng/service/$compile#directive-definition-object。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-20
    • 2016-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多