1

How can I get my directive to call to parent's controller function? I have a directive that look like this:

HTML:

<div ng-app="myapp" ng-controller="mainController as mainCtrl">
some body text<br>
    <a href="javascript:;" ng-click="mainCtrl.myfunc()">Click Me from body</a>
    <photo photo-src="abc.jpg" caption="This is so Cool" />
</div>

Javascript:

var app = angular.module('myapp',[]);

app.controller('mainController', function(){
    var vm = this;
    vm.myfunc = myfunc;

    function myfunc(){
        console.log("Log from 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 I click on Click Me from body link, it shows the console log message as expected. However, nothing happen when I click on Click Me from directive. How can I make it works?

2
  • 1
    use & to pass functions in to your scope, the same way you used @ to pass other parameters. Commented Jul 11, 2015 at 2:18
  • 1
    Check this videotutorial about isolated scopes. It contains a practical example of what you need and it might be useful for you egghead.io/lessons/angularjs-understanding-isolate-scope Commented Jul 11, 2015 at 2:20

1 Answer 1

1

You are using isolated scope, so you cannot directly access parent scope as they are not inherited to the isolated scope. You could use $parent though (by doing ng-click="$parent.mainCtrl.myfunc()"). However that gets ugly and it gets tightly coupled with its parent, Instead you 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 from directive</a></figure>',
        replace: true,
        scope: {
            caption: '@',
            photoSrc: '@',
            onClick: '&' //<-- Accept function binding and use it in the template
        }
    }

and register it at the consumer level, just so it becomes more reusable.

 <photo photo-src="abc.jpg" caption="This is so Cool" on-click="mainCtrl.myfunc()" />

Fiddle

You could also use child scope creation instead of isolated scope and directly call the parent controller method. Here is a demo

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.