【问题标题】:AngularJS Link function not calledAngularJS链接函数未调用
【发布时间】:2014-05-01 16:29:55
【问题描述】:

我正在尝试编写我的第一个 AngularJS 指令:一个涉及 link 函数的指令。该指令正在加载,但是当我在我的页面中使用它时,不会调用 link 函数。


这是小提琴:http://jsfiddle.net/jCUSh/115/

这是 HTML:

<div ng-app="biApp">
    <google-maps-symbol></google-maps-symbol>
</div>

和 JavaScript:

var appModule = angular.module('biApp', []);

appModule.directive('googleMapsSymbol', function () {
    console.log("Directive was run");
    return {
        link: function (scope, elem, attrs) {
            console.log("Link was called");
        }
    };
});


我敢打赌我做错了一些简单的事情。

【问题讨论】:

    标签: angularjs angularjs-directive


    【解决方案1】:

    angular 的默认设置是假设指令是attributes,而不是elements!您正在使用指令作为元素,因此您需要使用限制指定它。更新后的代码如下:

    appModule.directive('googleMapsSymbol', function () {
        console.log("Directive was run");
        return {
            restrict: 'E',
            link: function (scope, elem, attrs) {
                console.log("Link was called");
            }
        };
    });
    

    注意restrict: 'E',。祝你好运!

    更新你的小提琴: http://jsfiddle.net/j8ZZ4/

    【讨论】:

    • 谢谢,成功了。我感到困惑的原因是,如果我从小提琴中删除了 &lt;google-maps-symbol&gt; 元素,则不会执行第一个 console.log 语句。所以看起来 Angular 像我预期的那样将元素解释为指令。现在一切都说得通了。
    【解决方案2】:

    这不是你的情况,但是当你的指令命名不正确时可能会出现同样的问题。 要特别注意名称中的破折号。由于角度自动在它们之间转换,这是一个非常常见的错误。

    考虑这个模板

    <div>
      <div this-wont-work></div>
      <div this-will-work></div>
    </div>
    

    使用这个指令。

     angular
       .module('biApp')
       .directive('this-wont-work', () => ( { link: () => console.log('nope')} ))
       .directive('thisWillWork', () => ( { link: () => console.log('works')} ))
    

    【讨论】:

      【解决方案3】:

      我遇到了一个不同的问题:同一元素中的 ng-include 试图包含一个空字符串 (""),因此出于某种原因没有让指令 link()

      通过在ng-include 中提供一个页面,link() 被按预期调用。

      【讨论】:

        【解决方案4】:

        人们可能发生这种情况的另一个原因是指令的其他编译阶段之一存在运行时错误。

        ng.module(MODULE).directive('myDirective', [() => {
            return {
                link() {
                    // Never getting here
                },
                template() {
                    // Error here would mess things up
                },
                controller() {
                    // error here would mess things up
                }
            };
        }]);
        

        【讨论】:

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