javascript - Angular js, call module controller's method in the directive, which doesn't see it's scope by default -


here issue: have specified routes in application config like:

when('/url', {     controller: 'controller',     templateurl: 'url'   }); 

in view have only:

<div ng-view my-directive="fire()"></div> 

the important thing there no 'ng-controller="mycontroller"' attribute. when user loads url, controller fires , template filled model data , rendered well.

then have directive must following on same page: when click, 'controller' has execute function, data , add render template/add data existing.

the directive is:

myappmodule.directive('mydirective', function() {   return {     restrict: 'a',     templateurl: 'url',     replace: false,     link: function(scope, element, attrs) {         var raw = element[0];          element.bind('click', function() {                  console.log('loaddata');                 scope.$apply(attrs.fire);          });       }    }; }); 

the console.log firing, scope.$apply(attrs.fire) - fire() function inside "controller" doesn't. key tips are: if add ng-controller="controller" in html work, fire twice when page load. how tell directive execute "controller" fire method without using ng-controller="controller"?

you can use scope.$eval() this, call method.

link: function(scope, element, attrs) {     var raw = element[0];     var func = attrs.mydirective;   // gets value fire()      element.bind('click', function() {             console.log('loaddata');             scope.$eval(func);              // shouldn't need call $apply here             // since func executed within              // controller     }); } 

Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -