1

I'm trying to click on a button and trigger a function of another controller. The important part here is that I have two controllers DashboardController where I have a datatable with a button and with a onClick I call a function of the other Controller named DashboardDeviceController.

I'm doing this so when I click on the button I will open a new view with tabs where each tab will have graphs.

So I want when I click on my button to specify the tab which it will be open instead of "Consumptions" which is the active tab by default.

DasboardController

button inside datatableoptions

return icon = '<center><a class="state-link" data-state-id="' + data.id + '" ng-click="setActiveTab(\"consumptions\")"><i style="color:#ff0000; width:21px; height:21px" title="Consumptions threshold exceed" class="fa fa-warning"></i></a></center>';

and I try to do this but didnt work..

$rootScope.$on("setActiveTab", function(name, obj, event){
                $scope.parentmethod(name, obj);
            });

            $scope.parentmethod = function(name, obj, event) {
                // task
                console.log("name ",name);
                var btn = event.currentTarget;
                obj[btn.id]=true;
                console.log("btn ", btn);
                activeTab = name;
            }


DashboardDeviceController

controllerScope.activeTab = {
            consumptions: true,
            network     : false,
            ap          : false,
            modem       : false,
            system      : false,
        };


controllerScope.getActiveTab = function () {
            console.log("getActiveTab()");

            var activeTab = null;
            for(var tabName in controllerScope.activeTab) {
                if (controllerScope.activeTab[tabName]) {
                    activeTab = tabName;
                    break;
                }
            }
            return activeTab;
        }

        controllerScope.setActiveTab = function (name) {
            console.log("setActiveTab()");

            var activeTab = null;
            for(var tabName in controllerScope.activeTab) {
                if (controllerScope.activeTab[tabName] == name) {
                    controllerScope.activeTab = name;
                    break;
                }
            }
        }
Cátia Matos
  • 820
  • 1
  • 8
  • 26
  • Possible duplicate of [What's the correct way to communicate between controllers in AngularJS?](https://stackoverflow.com/questions/11252780/whats-the-correct-way-to-communicate-between-controllers-in-angularjs) – Sibiraj Sep 06 '17 at 09:13

4 Answers4

0

In angularjs , to have a reusable function or things, you have to create a service.

angular.module('myModule')
    .factory('myService', serviceFunction);

serviceFunction.$inject = [];

function serviceFunction() {
    return {
        reusableFunction1: function() {}
    };
}

In angularjs service (or factory) implement the buisiness logic of your application. You can have a service to manage authentication for example. After create your service(s), you can inject it in your controller to use his functions:

angular.module('myModule')
    .controller('myCtrl', myCtrl);

myCtrl.$inject = ['$scope', 'myService'];

function myCtrl($scope, myService) {
    myService.reusableFunction1();
}

I join links to service and factory official documentation if you want to get more:

https://docs.angularjs.org/guide/services

https://docs.angularjs.org/guide/providers

Antoine Amara
  • 645
  • 7
  • 11
0

Use BROADCAST/EMIT an ON to communicate

$scope.$emit('myCustomEvent', 'Data to send');

// firing an event downwards
$scope.$broadcast('myCustomEvent', {
  someProp: 'Sending you an Object!' // send whatever you want
});

// listen for the event in the relevant $scope
$scope.$on('myCustomEvent', function (event, data) {
  console.log(data); // 'Data to send'
});

EXAMPLE

plunkr: https://plnkr.co/edit/WemGxPytLLmPulml8xjK?p=preview

OR

You can use angular.extend to communicate/link between controllers

app.controller('DashboardController', function($scope, $controller) {
        angular.extend(this, $controller('DashboardDeviceController', {$scope: $scope}));
});
Sibiraj
  • 4,486
  • 7
  • 33
  • 57
  • And then with $scope I can have access to controllerScope.getActiveTab and controllerScope.setActiveTab right? And I just need to pass an argument in my botton ng-click inside setActiveTab?? – Cátia Matos Sep 06 '17 at 09:03
  • I tried to do in DashboardController var object = angular.extend(this, $controller('DashboardDeviceController', {$scope: $scope})) but object returns {} – Cátia Matos Sep 06 '17 at 09:16
  • don't assign that. you can directly use it in the main Controller. or use the broadcast/emit method. that will be easy – Sibiraj Sep 06 '17 at 09:18
  • I tried like I said in the post to use emit and on but I cant pass the event in the button ... so I'm trying another solution – Cátia Matos Sep 06 '17 at 09:19
  • I tried to do this https://plnkr.co/edit/EMoKkM3DjlpfA9ec9ru6?p=catalogue and inside $scope I have the activeTab property with a json object inside – Cátia Matos Sep 06 '17 at 09:32
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/153759/discussion-between-sibi-raj-and-andre-bastos). – Sibiraj Sep 06 '17 at 09:34
0

Communication between controllers is done though $emit + $on / $broadcast + $on methods.

return icon = '<center><a class="state-link" data-state-id="' + data.id + '" ng-click="setActiveTab($event)"><i style="color:#ff0000; width:21px; height:21px" title="Consumptions threshold exceed" class="fa fa-warning"></i></a></center>';

In the action of setActiveTab($event) in DashboardController you need to call the DashboardDeviceController function like below

Let's say you have

app.controller('DashboardDeviceController', ['$scope', '$rootScope'
    function($scope) {
        $rootScope.$on("CallParentMethod", function(){
           $scope.parentmethod();
        });

        $scope.parentmethod = function() {
            // task
        }
    }
]);
app.controller('DashboardController', ['$scope', '$rootScope'
    function($scope) {
        $scope.setActiveTab = function(event) {
            $rootScope.$emit("CallParentMethod", {});
        }
    }
]); 
Sangram Badi
  • 4,054
  • 9
  • 45
  • 78
0

The besat idea is this, First you need to check the priority of your controller, like They are communication :

1.parent to child communication

then do in your parent controller $scope.$broadcast('name',{objkey:value});
then do in your child controller $scope.$on('name',function(event,args){
//console the args params
});

2.child to parent communication:

then do in your child controller $scope.$emit('name',{objkey:value});
then do in your parent controller $scope.$on('name',function(event,args){
//console the args params
});
Kunvar Singh
  • 1,779
  • 2
  • 13
  • 21