1

I have created a simple directive to load a template. Within the template is a binding to a function in the controller that I wanted fired on ng-click.

The directive:

angular
    .module('myApp')
    .directive('someDirective', someDirective);

function someDirective() {
    var directive = {
        templateUrl: 'app/components/some-directive/some-directive.html',
        controller: 'MyCoolController',
        controllerAs: 'vm',
        restrict: 'A',
    };

    return directive;
}

The controller:

angular
    .module('myApp')
    .controller('MyCoolController', MyCoolController);

function MyCoolController() {
    var vm = this;

    function clickMe() {
        alert('clicked!');
    }

    cm.clickMe = clickMe;

}

The template:

<div my-cool-directive>
    <a href="#" ng-click="vm.clickMe()">Click me</a>
</div>

My issue is that the ng-click event is not firing when the a is clicked.

1

1 Answer 1

2

The issue was my lack of understanding how a directive inherits scope. Adding scope: true to the directive map corrects the scope for my use case.

angular
    .module('myApp')
    .directive('someDirective', someDirective);

function someDirective() {
    var directive = {
        templateUrl: 'app/components/some-directive/some-directive.html',
        controller: 'MyCoolController',
        controllerAs: 'vm',
        scope: true, // <-------- Gotcha!
        restrict: 'A',
    };

    return directive;
}

There are 3 different types of scopes for directives:

  1. Shared scope
  2. Inherited scope
  3. Isolated scope

For further information see this post: Understanding scopes in AngularJS custom Directives

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.