Robert J.
Robert J.

Reputation: 2701

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", ['ngFlatDatepicker'])
    .controller('mainController', ['$scope', mainController])
    .controller("machinesController", machinesController);;

    function mainController($scope) {
        $scope.datepickerConfig_From = {
            allowFuture: true,
            dateFormat: 'DD.MM.YYYY',
            minDate: moment.utc('2015-09-13'),
            maxDate: moment.utc('2015-09-17')
        };

        $scope.datepickerConfig_To = {
            allowFuture: true,
            dateFormat: 'DD.MM.YYYY',
            minDate: moment.utc('2015-09-13'),
            maxDate: moment.utc('2015-09-17')
        };

        $scope.date_from = "14.09.2015";
        $scope.date_to = "15.09.2015";

        $scope.change = function () {
            //somehow execute machinesController get function
        };

    }

    function machinesController($http) {
        var vm = this;
        vm.errorMessage = "";
        vm.machines = [];

        $http.get("/api/machine/2015-09-14_2015-09-16")
        .then(function (response) {
            //success
            angular.copy(response.data, vm.machines);
        }, function (error) {
            //failure
            vm.errorMessage = "Failed to load data:" + error;
        });

    }
})();

my machinesController is supposed to call a GET function with parameters. Here parameters are 2015-09-14 and second one is 2015-09-16 (for now they are hard coded).

What I would like to achieve is, that I have a two input controls on my main page, which trigger $scope.change function (located at the bottom of the first mainController). Here I would like to pass values of date_from and date_to to the GET function, so that I can retrieve certain values.

What I can do (in the end, if nothing works) is to copy the ode from machinesController into my mainController and that would solve the problem.

However I would like to learn how to work with this a bit better, therefore I would like to learn how to do it the proper way (in this case calling one module from the other).

What do I need to change in order to achieve this?

EDIT:

The reason why I have machinesController is, as was mentioned, to donwload the json data and show it to the user. So in the end in my html code I have the following:

    <div ng-controller="machinesController as vm" class="col-md-6 col-md-offset-3">
        <div class="text-danger" ng-show="vm.errorMessage"> {{ vm.errorMessage }}</div>
        <table class="table table-responsive table-striped">
            <tr ng-repeat="machine in vm.machines">
                <td> {{ machine.name }}</td>
            </tr>
        </table>
    </div>

Which displays a table with machine names.

Upvotes: 1

Views: 164

Answers (3)

GG.
GG.

Reputation: 21834

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]);

function mainController($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;
        });
    };

}

function MachinesService($http) {
    return {
        getMachines: getMachines
    };

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

Upvotes: 1

sreeramu
sreeramu

Reputation: 1223

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

Upvotes: 2

user3045179
user3045179

Reputation: 331

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/

Upvotes: 1

Related Questions