Skip to content Skip to sidebar Skip to footer

Invoke One Controller From Another

I am a total newbie in AngularJs, so please be patient with me. I have the following angular App, which contains two controllers (function () { angular.module('app-machines', [

Solution 1:

you can active this is two way:

First : $broadcast and $on

//PUBLISHER
angular.module('myApp').controller('CtrlPublish', ['$rootScope', '$scope',
function ($rootScope, $scope) {

  $rootScope.$broadcast('topic', 'message');

}]);

//SUBSCRIBER
angular.module('myApp').controller('ctrlSubscribe', ['$scope',
function ($scope) {

  var unbind = $scope.$on('topic', function (event, arg) { 
    $scope.receiver = 'got your ' + arg;
  });
  $scope.$on('$destroy', unbind);
}]);

Second : Through common service

angular.module('myApp', [], function($provide) {
    $provide.factory('msgBus', ['$rootScope', function($rootScope) {
        var msgBus = {};
        msgBus.emitMsg = function(msg) {
        $rootScope.$emit(msg);
        };
        msgBus.onMsg = function(msg, scope, func) {
            var unbind = $rootScope.$on(msg, func);
            scope.$on('$destroy', unbind);
        };
        return msgBus;
    }]);
});

and use it in controller like this:

controller 1

function($scope, msgBus) {
    $scope.sendmsg = function() {
        msgBus.emitMsg('somemsg')
    }
}

controller 2

function($scope, msgBus) {
    msgBus.onMsg('somemsg', $scope, function() {
        // your logic
    });
}

From : Post

Solution 2:

To takes care of downloading the data you should use a factory.

Look at this answer for further details about good practices.

I modified your code to use a factory.

angular.module("app-machines", ['ngFlatDatepicker'])
    .factory('MachinesService', ['$http', MachinesService])
    .controller('mainController', ['$scope', 'MachinesService', mainController]);

functionmainController($scope, MachinesService) {
    // date pickers config...$scope.date_from = "14.09.2015";
    $scope.date_to = "15.09.2015";

    $scope.change = function () {
        MachinesService.getMachines($scope.date_from, $scope.date_to).then(function (response) {
            vm.machines = response.data;
        }, function (error) {
            vm.errorMessage = "Failed to load data:" + error;
        });
    };

}

functionMachinesService($http) {
    return {
        getMachines: getMachines
    };

    functiongetMachines(from, to) {
        return$http.get("/api/machine/" + from + "_" + to);
    }
}

Solution 3:

Why dont u create a service instead of second controller and inject it into your main controller and use it.

May be you can refer this :

http://ilikekillnerds.com/2014/11/angularjs-call-controller-another-controller/

Post a Comment for "Invoke One Controller From Another"