Can One Angularjs Controller Call Another

How to call a function from another controller in AngularJS?

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

So in your case you want to call a method of Controller "One" inside Controller "Two", the correct way to do this is:

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

$scope.parentmethod = function() {
// task
}
}
]);
app.controller('two', ['$scope', '$rootScope'
function($scope) {
$scope.childmethod = function() {
$rootScope.$emit("CallParentMethod", {});
}
}
]);

While $rootScope.$emit is called, you can send any data as second parameter.

Can one AngularJS controller call another?

There are multiple ways how to communicate between controllers.

The best one is probably sharing a service:

function FirstController(someDataService) 
{
// use the data service, bind to template...
// or call methods on someDataService to send a request to server
}

function SecondController(someDataService)
{
// has a reference to the same instance of the service
// so if the service updates state for example, this controller knows about it
}

Another way is emitting an event on scope:

function FirstController($scope) 
{
$scope.$on('someEvent', function(event, args) {});
// another controller or even directive
}

function SecondController($scope)
{
$scope.$emit('someEvent', args);
}

In both cases, you can communicate with any directive as well.

Call one controller under another controller in angularjs

I think you misunderstood the responsibility of controllers in angular.

How to use controllers from angular docs:

Use controllers to:

  • Set up the initial state of the $scope object.

  • Add behavior to the $scope object.


Do not use controllers to:

  • Manipulate DOM — Controllers should contain only business logic.
  • Putting any presentation logic into Controllers significantly affects
    its testability.
  • Angular has databinding for most cases and directives
    to encapsulate manual DOM manipulation.
  • Format input — Use angular
    form controls instead.
  • Filter output — Use angular filters instead.
  • Share code or state across controllers — Use angular services instead.
  • Manage the life-cycle of other components (for example, to create
    service instances).

So if you want to create some block of reusable code, you just need to create an angular service, which will include function with needed logic. Then you can inject it to both controllers and they will have necessary functionality.

Example:

app.controller('LoginController', function ($scope, $cookieStore, helperService) {
$cookieStore.put('email', 'test@gmail.com');

$scope.wecomeMessage = helperService.getMessage();

});

// Home controller
app.controller('HomeController', function ($scope, $cookieStore, $location, helperService) {

$scope.wecomeMessage = helperService.getMessage();
});


app.service('helperService', function ($cookieStore) {

this.getMessage = function () {
return $cookieStore.get('email') != null ? $cookieStore.get('email') : "";
};

});

Calling a Function inside a Controller from another Controller - AngularJS

Make a common method in factory and inject it in controller where required and call factory method in controller.

Learn about factory and providers

app.factory('ThemeFactory', function() {

return {
updateTheme: updateTheme
};

function updateTheme(getTab) {
// DO something common here
}
});

app.controller('ThemeCtrl', ['$http', 'ThemeFactory',
function($http, ThemeFactory) {
var ctrl = this;
ctrl.updateTheme = ThemeFactory.updateTheme;
}
]);

app.controller('SkillThemeCtrl', ['ThemeFactory',
function(ThemeFactory) {
ThemeFactory.updateTheme(1); //This is not working. This function is in ThemeCtrl
}
]);

app.controller('ExpThemeCtrl', ['ThemeFactory',
function(ThemeFactory) {
ThemeFactory.updateTheme(2); //This is not working. This function is in ThemeCtrl
}
]);

Call function from another controller using Events in AngularJS

There's a couple reasons why your snippet doesn't work.

You don't instantiate otherController so there's no way it will execute any code at all. So you need to add a div with ng-controller="otherController"

Now that you have an instance of the 2 controllers, to communicate with $scope events ($emit, $broadcast, $on) they need to be nested because scope events depend on the hierarchy of elements.

$scope.$emit will register events to parent controllers.

$scope.$broadcast will register events to child controllers.

You can manipulate the snippet below by moving the nested div out and changing events type.

var myModule = angular.module('myapp', []);
myModule.controller('otherController', function($scope) { $scope.$on('ShowDialog', function(event) { alert("hello"); });});
myModule.controller('myController', function($scope) { $scope.OnClick = function() { alert("Done"); $scope.$broadcast('ShowDialog'); }});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div style="padding: 0 5px; height: 100%" ng-app="myapp"> <div style="padding: 0 5px; height: 100%" ng-controller="myController"> <input type="button" ng-click="OnClick()" value="Say Hello!" /> <div ng-controller="otherController"></div> </div></div>

Call a Controller angularjs in another Controller angularjs

You could do it with only one service and call service from both controllers. This is a basic example, you could add a constructor and pass it $scope for example it depends on what you want to accomplish.

'use strict';

/**
* Service
*/

angular.module('myApp.someService', [])
.factory("someService", function () {

return {
verify: function() {},
edit: function(iditem){
self.verify();
}
});

Then your controllers would look like this:

angular.module('myApp').controller('FirstController', ['$scope', 'someService', function($scope, someService) {

service.verify($scope);

}]);

angular.module('myApp').controller('SecondController', ['$scope', 'someService', function($scope, someService) {

service.edit(iditem);

}]);


Related Topics



Leave a reply



Submit