How To Call Method Of Angularjs Controller Outside Of Angularjs In Javascript

How to call method of AngularJS controller outside of AngularJS in javascript

Hello everybody,

today I want to write few words about AngularJS and js integration.

Recently I had opportunity to cowork with one guy, which is great in knowing javascript, but absolutely hates to learn and apply AngularJS. So, I had task in front of me, to give him sone kind of JS object, which he can use in order to execute some method of AngularJS controller.

So I had some AngularJS controller. 

here is the fragment of it:

'use strict';
 
var controller = 'toolBoxController';
 
angular
    .module('examples')
    .controller(controller, TbController);//register

Then I've added class ( in terms of javascript ):

(function (window, undefined) {
    function toolBoxObject() {

//this function finds controller, which is binded to toolBox div, and executes method of it
        this.unSelect = function () {
            var scope = angular.element('#toolBox').scope();
            scope.$apply(
                    function() {
                        angular.element('#toolBox').controller().unSelect();
                    }
                );
        }

And then in controller I had following method:

var tbObject = new ToolBoxObject();
 
function TbController() {
    var vm = this;
    vm.tb = tbObject;
    vm.ToolBoxButtons = new Array();
    tbObject.controller = this;
//etc.....

And then following method was intended for execution:

vm.unSelect = function () {
 //some kind of implementation
}

I'm ready to bet that you want to ask, why on earth it was needed to use 

var scope = angular.element('#toolBox').scope();

and not just execute mehtod of controller. Well, the answer is simple without scope, the method of controller was executed but results of execution wasn't displayable at screen, and with apply results was possible to show on the screen.

No Comments

Add a Comment
Comments are closed