Search code examples
javascriptangularjsangular-directive

How to call my own function inside an Angular Directive?


I'd like to call "myFunc()" inside my angular directive, how might I do this?

myApp.directive("test", function () {
 return {
   restrict: 'A',
     template: "<div class='box'></div>",
     myFunc: function() {
                console.log('myFunc');
       },
     link: function ($scope, element, attrs) {

         element.bind('click', function () {
               myFunc(); //<------------- doesn't work
       });
     }
    } // of return
});

Solution

  • You can't define the function as a property of your return value in your call to directive. It either needs to be defined before your return:

    myApp.directive('test', function() {
        var myFunc = function() {
            console.log('myFunc');
        };
    
        return {
            restrict: 'A',
            template: '<div class="box"></div>',
            link: function($scope, element, attrs) {
                element.bind('click', myFunc);
            }
        };
    };
    

    Or the same way inside of your link function.