Thursday, May 18, 2017

AngularJS How to call controller function from outside of controller component

Its not a good practice to call AngularJS function from outside of its scope. But sometimes we need it badly. So there is a way around to do this easily.

You should note that scopes are initialized after the page is fully loaded, so calling methods from outside of scope should always be done after the page is loaded. Else you will not get to the scope at all. Below is a small code snippet to how you can achieve this easily:

var targetID = document.getElementById("AngularController");
angular.element(targetID).scope().init("Outside Controller");

Where "init" is function named in your controller as below:

var app = angular.module("myApp", []);
app.controller("AngularController", function($scope, $window) {
    $scope.init = function(res) {
        console.log("INIT INVOKED=" + res);
    };

    $scope.init("Controller Itself");
});








You can download full example from the link.


No comments:

Post a Comment