I am me I am me - 1 month ago 5
AngularJS Question

Calling a method within a controller that's within a custom directive

Been trying to figure this out for too long now. Maybe someone can shed some light:

Am experimenting with custom directives and as an exercise I'm trying to create a method within the custom directive's controller that can be called from a simple button within the view. But the method isn't being called, even though I can see the method (using console) as a property within isolated scope object. Any ideas please?

HTML:

<my-dir>
<p>My dir content</p>
<p><button ng-click="hideMe()">Hide element with isolated scope</button></p>
</my-dir>


JS:

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

app.directive('myDir', function() {

return {
restrict: 'EA',
scope: {},
controller: ['$scope', function ($scope) {

$scope.hideMe = function(){

console.log('hideMe called');

};

}]
};
})

Answer

You have to declare your template inside the directive using template: property or inside an external .html file using templateUrl:"path/to/template.html"

Example using template :

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

app.directive('myDir', function() {
    return {
        restrict: 'EA',
        scope: {},
        template : '<p>My dir content</p><p><button ng-click="hideMe()">Hide me</button></p>',
        controller: ['$scope', function ($scope) {
            $scope.hideMe = function(){
                console.log('hideMe called');
            };
        }]
    };
})

Example using templateUrl :

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

app.directive('myDir', function() {
    return {
        restrict: 'EA',
        scope: {},
        templateUrl : 'my-dir.tpls.html',
        controller: ['$scope', function ($scope) {
            $scope.hideMe = function(){
                console.log('hideMe called');
            };
        }]
    };
})

Template : my-dir.tpls.html

<p>My dir content</p>
<p><button ng-click="hideMe()">Hide me</button></p>

HTML:

<my-dir></my-dir>
Comments