Call Function From Another Controller In A Button Onclick
Solution 1:
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", {});
}
}
]);
Solution 2:
In angularjs , to have a reusable function or things, you have to create a service.
angular.module('myModule')
.factory('myService', serviceFunction);
serviceFunction.$inject = [];
functionserviceFunction() {
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'];
functionmyCtrl($scope, myService) {
myService.reusableFunction1();
}
I join links to service and factory official documentation if you want to get more:
Solution 3:
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
});
Solution 4:
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}));
});
Post a Comment for "Call Function From Another Controller In A Button Onclick"