AngularJS Link function not called

前端 未结 4 1125
一整个雨季
一整个雨季 2021-01-04 04:18

I\'m trying to write my first AngularJS directive: one involving the link function. The directive is being loaded, but when I use it in my page the link<

相关标签:
4条回答
  • 2021-01-04 04:55

    The default for angular is to assume that directives are attributes, not elements! You are using a directive as an element so you need to specify this with the restrict. The updated code reads:

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

    Note the restrict: 'E',. Best of luck!

    Updating your fiddle: http://jsfiddle.net/j8ZZ4/

    0 讨论(0)
  • 2021-01-04 05:06

    I had a different problem: an ng-include in the same element was trying to include an empty string ("") and so didn't let the directive link(), for some reason.

    By having a page available in the ng-include, the link() was called as expected.

    0 讨论(0)
  • 2021-01-04 05:18

    It is not your case, but the same issue might occur when the naming of your directive is not correct. Be especially careful to dashes in the name. Since angular automagically transforms between them, it's a very very common mistake.

    consider this template

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

    with this directives.

     angular
       .module('biApp')
       .directive('this-wont-work', () => ( { link: () => console.log('nope')} ))
       .directive('thisWillWork', () => ( { link: () => console.log('works')} ))
    
    0 讨论(0)
  • 2021-01-04 05:18

    Another reason this could happen for people is that there is a runtime error in one of the other compilation phases for the directive.

    ng.module(MODULE).directive('myDirective', [() => {
        return {
            link() {
                // Never getting here
            },
            template() {
                // Error here would mess things up
            },
            controller() {
                // error here would mess things up
            }
        };
    }]);
    
    0 讨论(0)
提交回复
热议问题