Search code examples
javascriptangularjsbackbone.js

How can I execute a function in an angularJS controller from a backbone controller


I am working on a application originally created with backbone and jQuery, however due to client requirement, new modules are built with angular. Routing of the application is handled with backbone route and we have successfully integrated angular modules.

The actual problem is, I need to retrieve the current instance of a module in angular and execute a function from the controller of that module based on actions handled by a backbone controller.

Here is what my angular module and controller looks like:

//In chat.module.js
( function () {
angular
    .module( 'chat.module', [] );
})();

//In chat.controller.js
(function () {
angular
        .module('chat.module')
        .controller('chat.controller', ['profileFactory', '$filter', '$q', '$timeout', 'Position', 'Chat', chat]);

function chat(profileFactory, $filter,  $q, $timeout, Position, Chat) {
    var vm = this;
    vm.initChatFlag = false;

    vm.initChat = initChat;
    vm.setInformation = setInformation;


    function setInformation() {
        //handle business logic here
    }

    ...

In backbone, the module is created as follows:

        chatmodule: function () {
        var self = this;
        var element = angular.element(document.querySelector('#modalCallback'));
        var chat = angular.element(document.querySelector('#chatModule'));
        var isInitializedChat = chat.injector();

        var isInitialized = element.injector();
        if (!isInitialized) {
            angular.bootstrap($('#modalCallback'), ['app']);
        }
        if (!isInitializedChat) {
            angular.bootstrap($('#chatModule'), ['app']);
        }

        //TODO: chat.controller.setInformation() get access to fields like chat.controller.initChatFlag etc

The main app module is defined thus:

    (function(){
    angular
        .module('app',[
            'callback',
            'ui.bootstrap',
            '720kb.datepicker',
            'ngLocale',
            'directives.module',
            'interceptor',
            'directive.loading',
            'angularUtils.directives.dirPagination',
            'blog.module',
            'profile.module',
            'filters.module',
            'chat.module',
            'ui.toggle',
        ]);
})();

Solution

  • I was able to get access to the controller using answer from this post - https://stackoverflow.com/a/21997129/7411342

        var Chat = angular.element(document.querySelector('#chatModule')).scope();
    
        if(!Chat) return;
    
        if(Chat.chatCtrl.initChatFlag) {
            Chat.chatCtrl.setInformation();
        }else{
            console.log('Chat has not been initialized');
        }