Click here to Skip to main content
15,884,472 members
Articles / Programming Languages / Javascript
Tip/Trick

Angular - Calling Directive Method from Controller

Rate me:
Please Sign up or sign in to vote.
4.92/5 (7 votes)
10 Jan 2015CPOL1 min read 67.8K   7   6
This tip will cover an uncommon issue in Angular – calling a directive method from a controller.

Introduction

This tip will cover an uncommon issue in Angular – calling a directive method from a controller.

I’ve first encountered this issue when I worked with Angular and WinJS on an XBOX project. I needed to open the Settings popup on button click event, but this popup was placed in the directive.

Normally I would expose a public method in the directive and call it from the Controller, unfortunately that’s not so easy when working with JavaScript since it’s a dynamic language, and the directive is a DOM element.

The Problem

The main problem is that directive contained in the controller, which means that the controller recognizes the directive (the controller can call directives methods and pass parameters to him), but the directive has no idea about the controller that he placed in – since directive can appear multiple times in different parts of our program.

So, if you want to call a directives method from the controller, you would need to work around it.

The Solution

We will need to create an empty object in our controller and pass it to the directive as a parameter.

While receiving it in our directive – we’ll inject a method to it:

JavaScript
app.directive('myDirective', function () {
    return {
        restrict: 'E',
        scope: {
        /*The object that passed from the cntroller*/
        objectToInject: '=',
        },
        templateUrl: 'templates/myTemplate.html',

        link: function ($scope, element, attrs) {
            /*This method will be called whet the 'objectToInject' value is changes*/
            $scope.$watch('objectToInject', function (value) {
                /*Checking if the given value is not undefined*/
                if(value){
                $scope.Obj = value;
                    /*Injecting the Method*/
                    $scope.Obj.invoke = function(){
                        //Do something
                    }
                }    
            });
        }
    };
});

Declaring the directive in the HTML with a parameter:

HTML
<my-directive object-to-inject=" injectedObject"></ my-directive>

Our Controller:

JavaScript
app.controller("myController", ['$scope', function ($scope) {
    $scope.injectedObject = {};
}];

Adding a button that will invoke the method when clicking on it:

HTML
<input type='button' value='Click Me' ng-click='injectedObject.invoke();' />

Now we can call the methods from our controller!

Notice that the controller actually doesn’t know that invoke() method is implemented in our object, all it knows is that this object exists, otherwise we would get an exception while calling a method of undefined object.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Israel Israel
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionCalling Directive Method from Controller Pin
Member 1191935925-Nov-17 1:14
Member 1191935925-Nov-17 1:14 
PraiseAwesome! Pin
tahirk55520-Jan-17 22:16
professionaltahirk55520-Jan-17 22:16 
QuestionInjectedObj Pin
Prateek Shankar26-Jul-16 2:15
Prateek Shankar26-Jul-16 2:15 
AnswerRe: InjectedObj Pin
Pavel Durov26-Jul-16 4:12
professionalPavel Durov26-Jul-16 4:12 
SuggestionSpelling mistake Pin
Anurag Gandhi11-Jan-15 0:29
professionalAnurag Gandhi11-Jan-15 0:29 
GeneralRe: Spelling mistake Pin
Pavel Durov11-Jan-15 3:11
professionalPavel Durov11-Jan-15 3:11 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.