javascript - Angular directive calling parent controller function -


how can directive call parent's controller function? have directive this:

html:

<div ng-app="myapp" ng-controller="maincontroller mainctrl"> body text<br>     <a href="javascript:;" ng-click="mainctrl.myfunc()">click me body</a>     <photo photo-src="abc.jpg" caption="this cool" /> </div> 

javascript:

var app = angular.module('myapp',[]);  app.controller('maincontroller', function(){     var vm = this;     vm.myfunc = myfunc;      function myfunc(){         console.log("log myfunc");     } });  app.directive('photo',function(){     return {         restrict: 'e',         template: '<figure> <img ng-src="{{photosrc}}" width="500px">   <figcaption>{{caption}}</figcaption>    <a href="javascript:;" ng-click="mainctrl.myfunc()">click me</a></figure>',         replace: true,         scope: {             caption: '@',              photosrc: '@'         }     } }); 

http://jsfiddle.net/7q9v3zz2/

when click on click me body link, shows console log message expected. however, nothing happen when click on click me directive. how can make works?

you using isolated scope, cannot directly access parent scope not inherited isolated scope. use $parent though (by doing ng-click="$parent.mainctrl.myfunc()"). gets ugly , gets tightly coupled parent, instead can use function binding (&).

return {         restrict: 'e',         template: '<figure> <img ng-src="{{photosrc}}" width="500px">   <figcaption>{{caption}}</figcaption>             <a href="javascript:;" ng-click="onclick()">click me directive</a></figure>',         replace: true,         scope: {             caption: '@',             photosrc: '@',             onclick: '&' //<-- accept function binding , use in template         }     } 

and register @ consumer level, becomes more reusable.

 <photo photo-src="abc.jpg" caption="this cool" on-click="mainctrl.myfunc()" /> 

fiddle

you use child scope creation instead of isolated scope , directly call parent controller method. here demo


Comments

Popular posts from this blog

android - Gradle sync Error:Configuration with name 'default' not found -

java - Andrioid studio start fail: Fatal error initializing 'null' -

html - jQuery UI Sortable - Remove placeholder after item is dropped -