I'm trying since few hours to call a function from a controller to another controller.
I saw similar topics (I tried but I'm certainly too bad): What's the correct way to communicate between controllers in AngularJS? Can one controller call another?
But no concrete example like I'm looking for.
Controllers:
app.controller('Controller1', function($scope, $modal, $modalInstance, job, JobServices) {
$scope.job1 = function () {
JobServices.job1($scope.name)
.success(function(data, status, headers, config) {
// something
});
}
function doSomething(){
// How call test() from controller2 ?
}
}
app.controller('Controller2', function($scope){
function test(){
do a lot of things
}
}
What's the best and easiest way to do that ?
Thank you a lot
EDIT:
I already tried using something like that:
app.controller('Controller1', ['$scope', '$rootScope', function($scope, $rootScope, $modal, $modalInstance, job, JobServices) {
But I have error saying job1 is undefined...
-
You probably want to put your logic into a service/factory and call the function on it instead.Aleksey Solovey– Aleksey Solovey2017年12月14日 11:07:16 +00:00Commented Dec 14, 2017 at 11:07
-
Possible duplicate of $on and $broadcast in angularSajal– Sajal2017年12月14日 11:23:31 +00:00Commented Dec 14, 2017 at 11:23
-
My problem is I have a lot of errors when I use function($scope, $modal, $modalInstance, job, JobServices) to ['$scope', '$rootscope', function($scope, $rootscope, $modal, $modalInstance, job, JobServices) from my functions like job1 (see my edit)C.Norris– C.Norris2017年12月14日 13:16:40 +00:00Commented Dec 14, 2017 at 13:16
1 Answer 1
you could the $scope.$emit and $scope.$on, little bit like this
app.controller('Controller1', ['$scope', '$rootScope' function($scope) {
function doSomething(){
$rootScope.$emit("callController2", {});
}
}
app.controller('Controller2', ['$scope', '$rootScope' function($scope) {
$rootScope.$on("callController2", function(){
this.test();
});
function test(){
do a lot of things
}
}
Sign up to request clarification or add additional context in comments.
1 Comment
C.Norris
As I said upper I already tried that and I have error (saying it's undefined) using ['$scope', '$rootScope'... (see my edit)
default