This question already has answers here:
Passing data between controllers in Angular JS?
(18 answers)
Closed 6 years ago.
Below this code console.log is working properly. How to set this data another page using another controller.
$scope.selectedJsonObject=function(category)
{
console.log(category);
}
You can use Service to share the variable across two controllers,
angular.module('Shared', []);
angular.module("Shared").factory("myService", function(){
return {sharedObject: {data: "eran" } }
});
angular.module('Shared').controller('MainCtrl', function ($scope, myService) {
$scope.myVar = myService.sharedObject;
});
angular.module('Shared').controller('Secondtrl', function($scope, $http, myService) {
$scope.myVar = myService.sharedObject;
});
Working App
Related
This question already has answers here:
Caching a promise object in AngularJS service
(3 answers)
Closed 4 years ago.
I'm trying to wrap by head around when to use $q in AngularJS. I've been using it in all my services so far so when I call our Web API it works nicely. What I'm trying to do is cut down on all the calls to the API since I need the same data in multiple places and I've just been pinging the API every time I needed the data.
Right now I have a service, which gets the data and a helper file to help with related things about the data.
What I want is to use this helper factory to hold the data that's needed for every body which uses it.
I'm having trouble wrapping my head around assigning the value of data from the helper file if the data hasn't gotten back to me yet when AngularJS runs.
This is what I have so far.
(function() {
var app = angular.module("Test", []);
app.service("githubService", function($http, $q) {
var deferred = $q.defer();
this.getAccount = function() {
return $http.get('https://api.github.com/users/JonDoe');
};
});
app.factory("githubHelper", ["githubService", function(githubService) {
_gitHubInfo = {};
githubService.getAccount().then(function(data) {
_gitHubInfo = data;
});
return {
gitHubInfo: _gitHubInfo
};
}]);
app.controller("Dummy", ["$scope", "githubHelper", "githubService", function($scope, githubHelper, githubService) {
// How do I make it work this way?
$scope.value = githubHelper.gitHubInfo;
// This is what I'm using now
githubService.getAccount().then(function(data) {
$scope.value2 = data;
});
}]);
})();
.box {
border: 1px red solid;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="Test">
<div ng-controller="Dummy">
<div class="box">
{{value}}
</div>
<br />
<div class="box">
{{value2}}
</div>
</div>
</div>
What I want to do is just remove the githubService dependency from the Dummy controller and only have it present in the githubHelper factory so I can remove the dependency on githubService from all my controllers and instead use gitHubHelper.
What do I need to change in Dummy controller to have $scope.value be the data returned from githubService.getAccount()?
I have something like this in my project:
app.factory("githubHelper", ["githubService", function(githubService) {
var promise = null;
function getInfo() {
if (!promise) {
promise = githubService.getAccount();
}
return promise;
}
return {
getInfo: getInfo
};
}]);
githubHelper.getInfo().then(function(data) {})
githubHelper.getInfo().then(function(data) {})
githubHelper.getInfo().then(function(data) {})
...
You're almost there. The problem is that githubinfo doesn't get populated until after you access it. What you should do is almost exactly (see my comment above) what you're doing githubservice.getaccount, but in githubhelper.getaccount, instead. Set githubinfo to a $q.deferred, return githubinfo.promise from getaccount, and resolve the promise in the then
UPDATE: NOW WITH MORE CODE! (now that I'm not on mobile :-D)
(function() {
var app = angular.module("Test", []);
app.service("githubService", function($http, $q) {
this.getAccount = function() {
return $http.get('https://api.github.com/users/JonDoe');
};
});
app.factory("githubHelper", ["githubService", function(githubService) {
return {
gitHubInfo: $q(function(resolve, reject) {
githubService.getAccount().then(function(data) {
resolve(data);
}, reject);
}
};
}]);
app.controller("Dummy", ["$scope", "githubHelper",
function($scope, githubHelper) {
githubHelper.gitHubInfo.then(function(data) {
$scope.value = data;
});
}]);
})();
Now, written as-is I would never approve that as a PR for many reasons (code clarity re: return { someProp: function() { /* a bunch of code */} } .... usage of $scope should be avoided at all costs... and as mentioned, the $cacheFactory can and should handle this) , but you should be able to get the general gist of how something along these lines could work
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
I have a problem with angularjs.
I want to return values within the Facebook SDK functions but will not let me get them in variables.
The "perfil_nombre" and "perfil_foto" the variables returned as "undefined" and wish to send to the scope.
Any chance? I'm totally lost.
Excuse my bad English.
login.controller('inicio_ctrl', function($scope, $http, $timeout, $window)
{
var laspaginas;
var response;
var perfil_foto;
var perfil_nombre;
var resp;
$scope.FBLogin = function()
{
FB.login(function(response)
{
if(response.authResponse)
{
FB.api('/me', function(response)
{
perfil_nombre = response.name; //<<<<<-------- good
FB.api('/me/picture?redirect=false', function(resp)
{
perfil_foto = resp.data.url; //<<<<<-------- good
});
});
}
else
{
console.log('User cancelled login or did not fully authorize.');
}
},
{ scope: 'email, public_profile, manage_pages,publish_pages,read_insights,user_friends, publish_actions'});
$scope.perfil_foto = perfil_foto; //<<<<<-------- undefined
$scope.perfil_nombre = perfil_nombre; //<<<<<-------- undefined
});
Angular is designed as an MVC or MV* framework. As such it is generally better to separate your logic into a service and then inject the service into the controller. This way you can prevent negative interactions between Angular and other frameworks. It can be difficult to anticipate how Angular will interact with outside libraries.
The simplest way to do this is make your function work using just javascript and then wrap it in a .factory or .service.
For example
(function(){
'use strict';
login.factory('FBService', FBService);
FBService.$inject = [(/*What ever dependencies are needed*/)];
function FBService(/*What ever dependencies are needed*/){
//Build the profile object (I assume perfil translates to profile in english)
var profileObject;
//Add Javascript Logic Here
//Create Getters to obtain the data
function getFoto(){
return profileObject.foto;
}
//expose Getter
return {getFoto: getFoto}
}
})();
(function(){
'use strict';
login.controller('inicio_ctrl', inicioCtrl);
inicioCtrl.$inject = ["$scope", "$http", "$timeout", "$window", "FBService"];
function inicioCtrl($scope, $http, $timeout, $window, FBService){
var ctrl = this;
ctrl.login = function(){
ctrl.perfil_folo = FBService.getFoto();
}
}
})();
If you can get the Javascript to work outside of Angular then this will allow you to preserve the work and integrate it into Angular
This question already has answers here:
Share data between AngularJS controllers
(11 answers)
Closed 7 years ago.
I've been testing Angularjs for a project and I would like to know how to capture data on a controller from view and pass this data to another controller.
This pseudocode exemplifies what I want to do:
controller1('$scope', function($scope){
var val1 = $scope.dataFromView;
});
controller2('$scope', function($scope, controller1 ){
var val2 = controller1.val1;
//then do something with val1
});
You should use factories for this
app.factory('val1', function() {
// Your code goes here
});
And then in the controller, inject the factory.
app.controller('controller1', ['val1', function(val1) {
}]);
app.controller('controller2', ['val1', function(val1) {
}]);
I am using angular framework and trying to pass $scope to different controller in my app.
UPDATE:
My problem is I wan't obtain the $scope data until user click a button.
.controller('firstCtrl', function($scope) {
$scope.getTest = function(){
$scope.test1 = 'good.'
$scope.test2 = 'bad.'
…..more
}
})
I need to pass $scope object to different controller
.controller('secondCtrl', function($scope) {
console.log($scope.test1)
})
How do I do it? Thanks!
In order to share data between two controllers you need to use factory.
For more details, please watch this video: "AngularJS Video Tutorial: Sharing Data Between Controllers" by John Lindquist.
To share information between controllers, you use services. A service can be created like this:
//Create angular main app module
var app = angular.module('myApp', []);
//create a service
app.service('sharedService', function () {
this.test1 = [1, 2, 3, 4];
});
//one controller, injecting the service
app.controller('firstCtrl', function ($scope, sharedService) {
sharedService.test1[0] = 5;
console.log(sharedService.test1[0]) //5, 2, 3, 1
});
//two controller, injecting the same service
app.controller('secondCtrl', function ($scope, sharedService) {
sharedService.test[1] = 4;
console.log(sharedService.test1[0]) //5, 4, 3, 1
});
Here is an example I just created on jsFiddle:
http://jsfiddle.net/NHtFu/
Use custom events on the $rootScope
.controller('firstCtrl',['$rootScope', function($rootScope) {
$scope.getTest = function(){
$rootScope.your_object = {foo:bar}
$rootScope.$emit('custom_event');
}
}])
.controller('secondCtrl', function($scope,$rootScope) {
$rootScope.$on('custom_event',function(){
//do stuff
//$rootScope.your_object is available
})
});
You may need to unbind the root scope from that event if the controllers instantiate more then once
There may be an objection against 'polluting' the root scope but that's what its there for.
This question already has answers here:
Can one AngularJS controller call another?
(14 answers)
Closed 9 years ago.
How do I store the items I've selected in a checkbox with other controllers?
My attempt (see the plnkr for views):
script.js (controllers)
var myApp = angular.module('myApp', []);
myApp.factory('CooSelection', function () {
return {selectedCoo: []}
})
function CooListCtrl($scope, CooSelection) {
$scope.coos = {"Coos": ["spark", "nark", "hark", "quark"]};
$scope.coo_list_selection = CooSelection;
$scope.checkSelection = function (item) {
if ($scope.coo_list_selection.indexOf(item) === -1) {
$scope.coo_list_selection.push(item);
} else {
$scope.coo_list_selection.splice($scope.coo_list_selection.lastIndexOf(item), 1);
}
}
}
CooListCtrl.$inject = ['$scope', 'CooSelection'];
function DebugCooList($scope, CooSelection) {
$scope.coo_selection = CooSelection;
}
DebugCooList.$inject = ['$scope', 'CooSelection'];
When you reference the CooSelection service, you are expecting an array, but the factory returns an object. You could do this instead:
myApp.factory('CooSelection', function () {
return []; // Return an array instead of an object.
})
Also, in your DebugCooList controller, your scope property does not match the name of the variable you are checking in the view. The controller code assigns to coo_selection but the view checks coo_list_selection, so you'll need to change one to match the other.