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

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
}])

Related

$rootScope.$emit used in $http callback [duplicate]

This question already has answers here:
Why are Callbacks from Promise `.then` Methods an Anti-Pattern
(2 answers)
Why are AngularJS $http success/error methods deprecated? Removed from v1.6?
(2 answers)
Closed 4 years ago.
I understand the basic Javascripts callbacks, but I do not know what $rootScope.$emit 'dispatchQuery' is doing.
(function() {
angular.module('sp').factory('Object', [
'$rootScope', function($rootScope) {
var Object;
return Object = {
load: function(callback) {
return $http(method: "get", url: "http://myhost/bananas", options = {}).success(function(response) {
$rootScope.myItems = response.items;
return callback && callback();
});
}
};
}
]);
}).call(this);
it is called from main.js
sp.run [
'$rootScope','Object'
, function($rootScope, Object) {
Object.load = function(){ $rootScope.$emit 'Query'}
}]
$rootScope.$emit() dispatches event messages upward through the scope chain. Since $rootScope is at the top of the scope chain, only listeners on $rootScope will receive the event. Somewhere in your code, there should be a $rootScope.$on('Query', function(){...})
However, the syntax of your code seems wrong. The code below will generate a syntax error.
$rootScope.$emit 'Query'
Also, your factory creates a .load() method which is then replaced with a different method in your .run() block. Nowhere in your code sample is either method actually called.
Finally...you should avoid using the keyword Object. Consider giving your service factory a more meaningful name.

AngularJS: Why people prefer factory to share data between controllers [duplicate]

This question already has answers here:
AngularJS: Service vs provider vs factory
(30 answers)
Closed 5 years ago.
i am new in angular. so trying to know how to share data between two controller and search google. i visited few pages and found most of the time people use factory to share data. i just like to know can't we do it by service instead of factory ?
1st example
<div ng-controller="FirstCtrl">
<input type="text" ng-model="data.firstName">
<br>Input is : <strong>{{data.firstName}}</strong>
</div>
<hr>
<div ng-controller="SecondCtrl">
Input should also be here: {{data.firstName}}
</div>
myApp.factory('MyService', function(){
return {
data: {
firstName: '',
lastName: ''
},
update: function(first, last) {
// Improve this method as needed
this.data.firstName = first;
this.data.lastName = last;
}
};
});
// Your controller can use the service's update method
myApp.controller('SecondCtrl', function($scope, MyService){
$scope.data = MyService.data;
$scope.updateData = function(first, last) {
MyService.update(first, last);
}
});
2nd example
var myApp = angular.module('myApp', []);
myApp.factory('Data', function(){
var service = {
FirstName: '',
setFirstName: function(name) {
// this is the trick to sync the data
// so no need for a $watch function
// call this from anywhere when you need to update FirstName
angular.copy(name, service.FirstName);
}
};
return service;
});
// Step 1 Controller
myApp.controller('FirstCtrl', function( $scope, Data ){
});
// Step 2 Controller
myApp.controller('SecondCtrl', function( $scope, Data ){
$scope.FirstName = Data.FirstName;
});
examples are taken from this url Share data between AngularJS controllers
please guide me.
Both .service() and .factory() are both singletons as you’ll only get one instance of each Service regardless of what API created it.
Remember that .service() is just a Constructor, it’s called with new, whereas .factory() is just a function that returns a value.
Using .factory() gives us much more power and flexibility, whereas a .service() is essentially the “end result” of a .factory() call. The .service() gives us the returned value by calling new on the function, which can be limiting, whereas a .factory() is one-step before this compile process as we get to choose which pattern to implement and return.

passing ng repeat objects from one controller to other [duplicate]

This question already has answers here:
Passing data between controllers in Angular JS?
(18 answers)
Closed 6 years ago.
Hi i am displaying data using ng repeat.
I am displaying 3 persons in a template.. now when i click on 1 of them. I want to display in detail information of that person... so i need to make new controller and new template...but i know one way that is to pass one of the unique parameter like mobile no to the controller.. which then changes path with having mobile number to another controller and template.using location.path().search().. now in that 2nd controller i can request information again using 2nd parameter.. is this okay ??
I wanted to pass whole persons data from 1 controller to other but i don't know how can i do it...
Use a service to set the selected person's information and access the information using a routeParam for the user's unique id.
The code structure would look something like below
angular
.module('app')
.controller('ParentController', function (UserService) {
$scope.onSelect = function (user) {
UserService.setCurrentUser(user);
}
})
.controller('ChildController', function ($routeParams, UserService) {
$scope.user = UserService.getCurrentUser($routeParams.userId);
})
.factory('UserService', function () {
var currentuser = {};
return {
getCurrentUser: getCurrentUser,
setCurrentUser: setCurrentUser
};
function getCurrentUser () {
return currentuser;
}
function setCurrentUser (user) {
currentuser = user;
}
})
You can make the second controller child of the first controller.
All the data of the first controller can then be accessed in the second controller.
It also depends on the use cases, you can use the following methods to share data between controllers (if you do not want to do the above mentioned)
1) $localStorage
2) $sessionStorage
3) create a service

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

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

How to use an angular service into an non-angular object [duplicate]

This question already has answers here:
Call AngularJS from legacy code
(7 answers)
Closed 9 years ago.
I have an angular service
app.factory('MyService', function($http,$q)){
return{
super : function(){
return "Angular is awesome";
}
};
});
and a complex javascript object defined outside Angular's scope (controller or service):
var MyObject = {
anyFunction : function(){
alert(MyService.super());
}
};
Now, doing
MyObject.anyFunction();
of course fails. Any idea how I can get MyService injected into my external javascript object?
This is bad way, byt you may save your angular's var to the localStorage and then acces it from legacy code, and as a second option, you may access global variable from factory, using $window service.
In common js:
var myVar;
In factory:
app.factory('MyService', ['$window', '$http', '$q',function($window, $http, $q)){
return{
super : function(){
$window.myVar = 'that is it';
//or
//localStorage.addItem('myVar', 'varValue');
}
};
}]);
after MyService.super is done, you may access var in common js as usualy before

Resources