Exchanging data between controllers in angularjs [duplicate] - javascript

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

Related

How to set console data [duplicate]

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

AngularJS with Facebook SDK [duplicate]

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

How do I pass value to different controller in Angular js

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.

Force angular scope to update from service

I've create an angular controller and service. In my service I have an array that starts off blank when the app loads, but is filled later on. In my controller I have a property on $scope that points to that array. When the array in the service is updated I assumed the $scope property would also be updated and the DOM would update accordingly. Here is the sample code.
app.controller("myCtlr", ["$scope", "$service", function($scope, $service){
$scope.friends = $service.friends
}]);
app.factory("$service", function($http){
var friends = {};
friends = {
get: function(){
$http.get("/someurl").success(function(data){
// data is the array of friends
friends = data;
});
}
};
});
I've tried using angular.extend but there aren't many good example of it online so I don't fully understand it yet. Any help is much appreciated. Thanks!
Angular $http automatically kicks off a digest cycle, you should also return friends from your service and also use .then to continue the promise pattern:
app.factory("$service", function($http){
var friends = {};
friends = {
get: function(){
$http.get("/someurl").then(function(data){
return data.data
});
}
return friends;
});
And in your controller:
$service.friends.get().then(function(data) {
console.log(data);
});

Sharing data between AngularJS controllers? [duplicate]

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.

Categories

Resources