简体   繁体   中英

Link function not getting run in AngularJS directive

I'm having trouble with an angular directive. It doesn't seem to run the link function.

I feel like it's something obvious, but I just can't figure it out.

The directive is required as seen from below

angular.module('test').requires // ["injectedModule"]

Code below. Fiddle .

Any help would be amazing.

 angular .module('test', ['injectedModule']) .controller('tester', [ function() { this.test = function(data) { alert(data); } } ]); angular .module('injectedModule', []) .directive('testing', [ function() { return { restrict: 'E', scope: true, link: function(scope, element, attrs) { alert(scope, element, attrs); } }; } ]); 
 <div ng-app="test"> <div ng-controller="tester as t"> <video id="test" ng-src="https://scontent.cdninstagram.com/hphotos-xfa1/t50.2886-16/11726387_1613973172221601_1804343601_n.mp4" testing="t.test(el)" /> </div> </div> 

Looks to me like

restrict: 'E',

should be

restrict: 'A',

Your directive isn't being called at all as it is.

I think the error is in the restriction you are giving to your directive. You are restricting your directive to match only element (in other words tag). You should restrict to match attribute 'A'. Here's angular official documentation https://docs.angularjs.org/guide/directive and here's your fiddle working

Code sample:

angular
.module('injectedModule', [])
.directive('testing', [
  function() {
    return {
      restrict: 'A',
      scope: true,
      link: function(scope, element, attrs) {
        alert(scope, element, attrs);
      }
    };
  }
]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM