Ben Aston
Ben Aston

Reputation: 55729

Accessing the controller associated with a directive instance

I have associated a controller with a directive like so:

return function MyDirective() {
    return {
        scope: {},
        restrict: 'E',
        template: template,
        controller: 'myController',
        replace: true,
    };
};

If I want to access a method on the controller from the template, do I need to add the controller to a property on the scope?

Template:

<div> 
  <div> 
    <button ng-click="doSomething()">Do something.</button>
  </div>
</div> 

Controller:

function MyController() {}

MyController.prototype.doSomething() {
  window.alert('foo');
}

Upvotes: 1

Views: 34

Answers (1)

Shaishab Roy
Shaishab Roy

Reputation: 16805

You should avoid scope: {} from your directive to access controller functions because of scope: {} in your directive create isolate scope from your controller.

That's why you may can not access controller functions from your directive template.

after avoid scope: {} use functions like normal controller functions.

Like:

<button data-ng-click="myFunction()">call my function</button>

you can use scope in link function in your directive.

link: function (scope, element, attrs)

Upvotes: 1

Related Questions