How to call a function from another controller in AngularJS? [duplicate] - angularjs

This question already has answers here:
Can one AngularJS controller call another?
(14 answers)
How do I inject a controller into another controller in AngularJS
(7 answers)
Closed 7 years ago.
I need to call a function in another controller in AngularJS. How can I do this?
Code:
app.controller('One', ['$scope',
function($scope) {
$scope.parentmethod = function() {
// task
}
}
]);
app.controller('two', ['$scope',
function($scope) {
$scope.childmethod = function() {
// Here i want to call parentmethod of One controller
}
}
]);

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.

I wouldn't use function from one controller into another. A better approach would be to move the common function to a service and then inject the service in both controllers.

You may use events to provide your data. Code like that:
app.controller('One', ['$scope', function ($scope) {
$scope.parentmethod=function(){
$scope.$emit('one', res);// res - your data
}
}]);
app.controller('two', ['$scope', function ($scope) {
$scope.$on('updateMiniBasket', function (event, data) {
...
});
}]);

If the two controller is nested in One controller.
Then you can simply call:
$scope.parentmethod();
Angular will search for parentmethod function starting with current scope and up until it will reach the rootScope.

The best approach for you to communicate between the two controllers is to use events.
See the scope documentation
In this check out $on, $broadcast and $emit.

If you would like to execute the parent controller's parentmethod function inside a child controller, call it:
$scope.$parent.parentmethod();
You can try it over here

Related

How to get data from scope by rootscope

I got an app.run where i get my data from an webintent. In the app.run i'm not allowed to use $scope so i use $rootscope.Now my $scope got $scope.sendURL(Object) and I want to make this call inside my app.run.
I searched a lot on stackoverflow and google and I came acros $broadcast and $emit. But i can't figure out if that is right thing to do. Does somebody know what i should try?
edit:
I need to call the $scope.sendURL inside app.run and i have no idea how to do it. I searched on stackoverflow and came acros $broadcast and $emitbut i'm not use if i need to use them.
Move the logic into a factory and use the factory in run and in your controller:
var app = angular.module('myApp', []);
app.run(function (myFactory) {
var data = {};
myFactory.sendURL(data);
});
app.controller('MyController', function ($scope, myFactory) {
$scope.sendURL = myFactory.sendURL;
});
app.factory('myFactory', function ($http) {
return { sendURL : sendURL };
function sendURL(data) {
// Put the logic here
console.log(data);
}
});

How to pass values from one controller to another controller [duplicate]

This question already has answers here:
Share data between AngularJS controllers
(11 answers)
Closed 6 years ago.
I have
1.) Controller1.js ( which has an array named Arr )
2.) Controller2.js
How should I pass Arr from Controller1.js to Controller2.js?
There are 2 ways to do it, best practice is to create service and store the value in it, and then inject it to both controllers. The angular service is singleton. You can read more here about services.
Second (and not good) way is to use $rootScope.
angular.module('myApp')
.controller('myController1', ['myService', function (myService) {
//myService.array
}])
.controller('myController2', ['myService', function (myService) {
//myService.array
}])
.service('myService', [function () {
var service = {};
service.array = [];
return service
}])

What is the difference between two scopes in the same controller (one from a service) to a directive?

I've got the below controller with two scope variables and only one passes through to my directive?
.controller('newsController', ['$scope', 'gasPrices',
function($scope, gasPrices) {
gasPrices.success(function(data) {
$scope.gasFeed = data.series[0];
});
$scope.myData02 = [2.095,2.079,2.036,1.988,1.882,1.817,1.767,1.747];
}])
;
I've got a directive that accepts one scope but not the other?
This works
<line-chart chart-data="myData02"></line-chart>
This doesn't
<line-chart chart-data="gasFeed"></line-chart>
Do you know why?
You have to delay instantiating the directive until the data from your async service is available. Something like:
<line-chart ng-if="gasFeed" chart-data="gasFeed"></line-chart>
This should not instantiate the directive until the gasFeed scope property has data.
Try this:
.controller('newsController', ['$scope', 'gasPrices',
function($scope, gasPrices) {
//Create a object that will be pass in the directive, then when this variable
//it's loaded, the value in the directive (if the scope of the directive uses the '=' binding) will be updated
$scope.gasFeed = {};
gasPrices.success(function(data) {
$scope.gasFeed = data.series[0];
});
$scope.myData02 = [2.095,2.079,2.036,1.988,1.882,1.817,1.767,1.747];
}]);
Yes.
Here, in your example you can access gasFeed scope only when when there is a success callback from the service. Hence, till then myData02 scope will be loaded.
If you want to access both. Then try this :
.controller('newsController', ['$scope', 'gasPrices',
function($scope, gasPrices) {
gasPrices.success(function(data) {
$scope.gasFeed = data.series[0];
$scope.myData02 = [2.095,2.079,2.036,1.988,1.882,1.817,1.767,1.747];
});
}]);

How to Forward $scope from Controller to Controller AngularJS?

I am New to Angular Js.
Is It Possible to Forward Scope of the RestaurantController to MenuController Code as Follows
Example :-
angular.module('restaurants').controller('RestaurantController', ['$scope',
function($scope) {
$scope.restaurantid="435scvcxvbrcvbnvn";
}
]);
And i assigned restaurant id as New scope in Menu Controller as Follows
angular.module('menus').controller('MenuController', ['$scope',
function($scope) {
$scope.currentrestaurantid= $scope.restaurantid;
alert($scope.currentrestaurantid); // showing Null
}
]);
The Restaurant Id is not Persisted .. Honestly i feel that some thing is Missing .
How to Get the Id From Restaurant controller to Menu Controller ?
Try inheritance
angular.module('restaurants', []);
angular.module('menus', ['restaurants']);
angular.module('restaurants').controller('RestaurantController', function($scope) {
$scope.restaurantid="435scvcxvbrcvbnvn";
});
angular.module('menus').controller('MenuController', ['$scope','$controller',
function($scope, $controller) {
$controller('RestaurantController', {$scope: $scope});
$scope.currentrestaurantid= $scope.restaurantid;
}
]);
Working fiddle
I propose use the rootScope to do that.
Use the $broadcast to notify the other controller the change on the firsts controller scope.
$rootScope.$broadcast("restIDUpdated", {
restaurant: $scope.restaurantid
});
Use the $on to receive the notification in the second controller about the event that happend in the first controller.
$scope.$on("restIDUpdated", function (event, args) {
$scope.restaurant = args.restaurant;
});
There is an example of this here
Try something like this.
angular.module('restaurants').controller('RestaurantController', function($scope) {
$rootScope.$broadcast("restIDUpdated", {
restaurantid: 435scvcxvbrcvbnvn
});
});
angular.module('menus').controller('MenuController', ['$scope','$controller',
function($scope, $controller) {
$controller('RestaurantController', {$scope: $scope});
$scope.$on("restIDUpdated", function (event, args) {
$scope.currentrestaurantid= args.restaurantid;
});
}
]);
But to be honest I am not sure if this mechanism works with two different angular apps, I know using the same module it works but not sure what is going to happen using two different modules, but take a look at the API
A pattern I commonly use is to create an angular service and inject it into controllers I want to share data with. something like this...
angular.module('restaurants', []);
angular.module('menus', ['restaurants']);
angular.module('restaurants').service('RestaurantService', function() {
this.restaurantid = "435scvcxvbrcvbnvn";
});
angular.module('restaurants').controller('RestaurantController', function($scope, RestaurantService) {
$scope.restaurantid = RestaurantService.restaurantid;
});
angular.module('menus').controller('MenuController', function($scope, $controller, RestaurantService) {
$scope.currentrestaurantid = RestaurantService.restaurantid;
});
As said here, injectable service as generic way for your situation.
But I'd like to point more pretty way, using markup and controller as (docs) expression.
For example you have following controller:
.controller('RestaurantController', function($scope) {
$scope.restaurantid="435scvcxvbrcvbnvn";
})
and you can bind it to variable in the scope:
<div ng-controller="RestaurantController as restaurant">
<div ng-controller="MenuControllerOrAnyOther">
restaurant id = {{restaurant.restaurantid}}
</div>
</div>
Remarks
This approach would be nicer if you need restaurantid ONLY in markup, e.g.
<button ng-click="select(restaurant.restaurantid)">
This looks ugly, if you want to use restaurantid in js code (you should use injectable services then):
var restaurantid = $scope.$eval('restaurant.restaurantid');

Inject factory into controller function in angularjs

I am trying to code a factory and use it on a controller
.controller('View2Ctrl', ['$scope', 'Alert', function($scope, Alert) {
this works inside the controller but when I am trying to access it inside a function it's undefined.
$scope.test_function = function(Alert) {
Alert.some_method -> undefined.
};
$scope.test_function = function() { // remove Alert
Alert.some_method -> undefined.
};
if you inject the service into a controller you dont need to inject into a function inside that controller
check this one :)

Resources