Unable to sync AngularJS service with controllers (angular.copy) - javascript

I have set up two controllers (Controller A and Controller B) and a service (Service). I am attempting to sync the data from controller A to the service, and present that information to Controller B.
Within my Service, I've established a variable confirmdata and get and set functions:
function setData(data) {
confirmdata = angular.copy(data);
}
function getData() {
return confirmdata;
}
In controller A I've created a function syncto sync information from the controller to the service:
this.sync = function () {
var data = {
payment: this.getpayment()
}
Service.setData(data);
In controller B I've assigned a function as:
this.sync = function () {
this.viewData = Service.getData();
console.log('TestingData', this.viewData);
For a reason I am unaware of; my console log simply returns undefined when it should be returning the results of the getpayment() function. Am I missing something here?

The fact that you are getting undefined would indicate that you haven't initialized 'confirmdata' in your service. Whether this is the actual issue though, isn't clear. For a simple example, I would design your service like this:
myApp.factory('sharedService', [function () {
var confirmdata = {};
return {
setData: function (newData) { confirmdata = newData; },
getData: function getData() { return confirmdata; }
}
}]);
Take a look at this plunker. It gives an example of data being shared between controllers via a service.

Related

Passing data between controller via service won't work

I'm trying all the approaches passing data between controllers using service, factory or broadcast. None of them works for me. I follow the exact solution online, but still unfortunate. I placed service inside my app.js.
App.JS
myApp.service('customService', [function () {
this.list = [];
this.setObject = function (o) {
this.list.push(o);
},
this.getObject = function () {
return this.list;
}
}]);
Controller #1
myApp.controller('Controller1', function ($scope, customService) {
customService.setObject({..});
$window.open("/controller2", '_blank');
}
Controller #2
myApp.controller('Controller2', function ($scope, customService) {
console.log(customService.getObject()); // Returns []
}
Problem
It returns [] on controller 2 from controller 1, instead of object data.
You should modify your service for storing a object under some specific key, and then retrieve it later given that key. You can define these keys whatever you like. I defined them in the same service so I can reuse them through all controllers. Something like this
Service
myApp.service('customService', [function () {
this.keys = {"foo": "foo", "bar": "bar"};
this.list = {};
this.setObject = function (obj, key) {
this.list[ley] = obj;
},
this.getObject = function (key) {
return this.list[key];
}
}]);
Controller #1
myApp.controller('Controller1', function ($scope, customService) {
customService.setObject({"propX": "propX"}, customService.foo);
//$window.open("/controller2", '_blank');
/* I encourage you to use something like ngRoute here for navigating
* so, you should do something like $location.path('/controller2');
*/
}
Controller #2
myApp.controller('Controller2', function ($scope, customService) {
console.log(customService.getObject(customService.foo));
}
Are your controllers in the same page ?
Angular.js only works and keeps data on a single page. If your page reloads
(as you seem to indicate when you say "express.js loads the next
page", then it reinitialized everything.
You should either:
look at how to use Angular.js routing
(http://docs.angularjs.org/tutorial/step_07) so that you stay on the
same page. use something to persist your data, such as localstorage.
Find out more: http://diveintohtml5.info/storage.html
ref : Using angular service to share data between controllers
have you used routing? if u use then your code should be work.

Passing variables between controllers using AngularJS

I have two controllers: Controller1 and Controller2
In Controller1's $scope, I have set up all my values I need. Using the data in $scope, I'm trying to run certain functions and pass the return values to Controller2.
I was thinking about making a factory to pass variable from Controller1 to Controller2. However, I realized all input values I need lives in Controller 1. I wonder whether factory can persist the data when it runs in Controller1 and return that data when it runs again in Controller2.
Thanks
Factory is a singleton so it can be used to share data among different controllers or directives. Take a look at the fiddler here. I have created a factory 'sharedContext' which can be used to share any key-value pair across controllers using different $scope.
Factory
myApp.factory("sharedContext", function() {
var context = [];
var addData = function(key, value) {
var data = {
key: key,
value: value
};
context.push(data);
}
var getData = function(key) {
var data = _.find(context, {
key: key
});
return data;
}
return {
addData: addData,
getData: getData
}
});
From the controller that needs to share the object can call the 'addData' method of the factory to store the data under a key. The other controllers/directives which are interested in accessing the shared data can do so by calling the 'getData' method and passing the correct key.
Controller (Sharing Data)
function MyCtrl_1($scope, sharedContext) {
$scope.input_1 = 5;
$scope.input_2 = 15;
$scope.add = function() {
$scope.result = $scope.input_1 + $scope.input_2;
sharedContext.addData("Result", $scope.result)
}
}
Controller (accessing shared data)
function MyCtrl_2($scope, sharedContext) {
$scope.getData = function() {
$scope.result = sharedContext.getData("Result").value;
}
}
The only assumption here is that both the controllers need to use the exact key to share the data. To streamline the process you can use a constant provider to share the keys. Also note that I have used underscore.js to look for the key in the shared context dictionary.
This is the simplest solution that you can come up with. As you can see the factory is a simple object and because of that construct it's passed by reference not by value that means in both controller dataFactory is the same
http://plnkr.co/edit/eB4g4SZyfcJrCQzqIieD?p=preview
var app = angular.module('plunker', []);
app.controller('ControllerOne', function (dataFactory) {
this.formFields = dataFactory
});
app.controller('ControllerTwo', function (dataFactory) {
this.formData = dataFactory
});
app.factory('dataFactory', function () {
return {};
})
edit
app.factory('dataFactory', function () {
var factory = {
method1: function (arg) {
console.log('method1: ', arg)
factory.method2('called from method1')
},
method2: function (arg) {
console.log('method2: ', arg)
}
}
return factory;
})

Using http requests, promises, ng-options, and factories or services together

I'm trying to retrieve a list of options from our database and I'm trying to use angular to do it. I've never used services before but I know that's going to be the best way to accomplish what I want if I'm going to use data from my object in other controllers on the page.
I followed a couple tutorials and put together a factory that makes an http request and returns the data. I've tried several ways of doing it, but for some reason nothing is happening. It's like it never runs the factory function and I can't figure out why.
Factory:
resortModule= angular.module('resortApp',[]);
resortModule.factory('locaService',['$http', function ($http){
var locaService= {};
locaService.locations = {};
var resorts = {};
locaService.getLocations=
function() {
$http.get('/url/url/dest/').success(function (data) {
locaService.locations = data;
});
return locaService.locations;
};
return locaService;
//This is a function I would like to run in addition to the first one so multiple variables would be stored and accessible
/*getResorts:
function(destination) {
$http.get('/url/url/dest/' + destination.id).success(function (data) {
resorts = data;
});
return resorts;
}*/
}]);
resortModule.controller('queryController',['$scope', 'locaService', function($scope, locaService) {
$scope.checkConditional= function (){
if($("#location").val() == ""){
$("#location").css('border','2px solid #EC7C22');
}
};
$scope.selectCheck= function (){
$("#location").css('border','2px solid #ffffff');
$(".conditional-check").hide();
};
$scope.resort;
$scope.locations= locaService.getLocations();
}]);
I just want the data to be returned and then assigned to the $scope.locations to be used for ng-options in the view. Then I want my other function to run on click for the next field to be populated by the variable resort. How would I do this? Any help would be great! Thanks!
$http service returns a promise, and your function should return that promise. Basically your getLocations function should be something like the following
locaService.getLocations=
function() {
return $http.get('/url/url/dest/');
};
Then in your controller you should retrieve the options using this promise:
locaService.getLocations()
.then(
function(locations) // $http returned a successful result
{$scope.locations = locations;}
,function(err){console.log(err)} // incase $http created an error, log the returned error);
Using jquery in controllers or manipulating dom elements in controllers is not a good practice, you can apply styles and css classes directly in views using ng-style or ng-class.
Here is an example how all it should look wired up:
resortModule= angular.module('resortApp',[]);
resortModule.factory('locaService',['$http', function ($http){
var locaService= {
locations: {}
};
var resorts = {};
locaService.getLocations= function() {
return $http.get('/url/url/dest/');
};
return locaService;
//This is a function I would like to run in addition to the first one so multiple variables would be stored and accessible
/*getResorts:
function(destination) {
$http.get('/url/url/dest/' + destination.id).success(function (data) {
resorts = data;
});
return resorts;
}*/
}]);
resortModule.controller('queryController',['$scope', 'locaService', function($scope, locaService) {
/* Apply these styles in html using ng-style
$scope.checkConditional= function (){
if($("#location").val() == ""){
$("#location").css('border','2px solid #EC7C22');
}
};
$scope.selectCheck= function (){
$("#location").css('border','2px solid #ffffff');
$(".conditional-check").hide();
};
*/
$scope.resort;
locaService.getLocations()
.then(
function(locations) // $http returned a successful result
{$scope.locations = locations;}
,function(err){console.log(err)} // incase $http created an error, log the returned error);
}]);

Best way to store and use data in Angular that updates periodically

I'm new to Angular and I'm trying to create an app that pulls data from a dynamically generated JSON file every 5 minutes and updates the view with the new data. The JSON file contains all the data for the website, which is data for a slider and for a list of events. I've read that global data can be stored in the $rootScope, or retrieved and served using a .service or .factory. I've tried different ways with no success and I'm lost. What is the best way to periodically pull data from an api for the entire app, store it, and use it?
Currently I have this code:
app.factory("Poller", function Poller($http, $timeout){
var data = {'slider' : [], 'activities' : []};
var getData = function(){
$http.get('http://example.com/json.php')
.then(function(r){
data = r.data;
});
$timeout(getData, 1000*60*5);
}
getData();
return{
data: data
}
});
app.controller('ListController', function(Poller){
this.activities = Poller.data.activities;
});
I think you're looking for something like this:
See plnkr
app.factory("Poller", function Poller($http, $interval){
var data = {
'newData': {
'one' : '',
'key' : ''
},
'fetchCount': 0
};
var getData = function() {
data.fetchCount += 1;
$http.get('http://echo.jsontest.com/key/value/one/two')
.then(function(response){
data.newData = response.data;
});
};
var loopGetData = function() {
$interval(getData, 5000);
};
loopGetData();
return{
data: data,
};
});
app.controller('ListController', function($scope, Poller){
$scope.activities = {'one' : '', 'key' : ''};
$scope.Initialize = function () {
$scope.$watch(function () { return Poller.data.newData; },
function(newValue, oldValue) {
if (newValue !== oldValue) {
$scope.activities = newValue;
}
});
};
$scope.Initialize();
});
app.controller('CountController', function($scope, Poller){
$scope.fetchCount = 0;
$scope.Initialize = function () {
$scope.$watch(function () { return Poller.data.fetchCount; },
function(newValue, oldValue) {
if (newValue !== oldValue) {
$scope.fetchCount = newValue;
}
});
};
$scope.Initialize();
});
So the problem here looks like you have defined the function getData() inside the Poller factory that makes the ajax request, but didn't bind that to a key inside the factory's returning object.
Try adding this,
return{
data: data,
getData: getData
}
And then remove the getData() you have right before the returning block.
Now I feel like depending on your app's setup, if you want to achieve long polling effects, you should attach getData() to a variable in some top-level controller that is always present so that you can invoke the getData() periodically using $timeout.
Speaking of $timeout is that you should extract the $timeout outside of the getData() and so that the function itself simply makes the ajax request. More modular, single responsibility design that way, which makes that factory function more usable in other areas of your app if you ever need.
If you want to update the information after you finish the ajax requests every five minutes, you should looking into $broadcast and $rootScope, you can basically tell your entire Angular app that some rootScope variable or service has changed, and they will update accordingly. You need some kind of callback set up after the ajax request inside whichever controller you are invoking the getData() function.

Angular, "activate" a watch after data has come in

I am trying to have a $watch on a scope so I Can listen for changes, however, I do not want the watch to start listening until the data has come in and populated. I am using a $q factory and then to populate the items, then I want the watch to start listening after everything is populated. I can't seem to get down how to control these order of events.
SO I have in my controller -
//call to the $q factoy to execut all http calls
getDefaults.resource.then(function(data){
//fill in scopes with data
$scope.allAccounts = data[0].data.accounts;
//THEN watch the scope for changes
$scope.$watch('selectedResources', function (newValue) {
//do action on change here
});
}
SO I'm wondering if there is any way to control these order of events in angular. Thanks for reading!
You can create a service for your xhr calls:
.factory('xhrService', function ($http) {
return {
getData: function () {
return $http.get('/your/url').then(cb);
}
};
function cb(data) {
/// process data if you need
return data.accounts;
}
});
after that you can use it like this inside your controller:
.controller('myController', function (xhrService) {
$scope.allAccounts = [];
xhrService.getData()
.then(function (accounts) {
$scope.allAccounts = accounts;
return $scope.allAccounts;
})
.then(function () {
$scope.$watch('allAccounts', function (newValue) {
// do something
}
});
});
I think this is a good way to structure your code because you can reuse your service and you can add (or not) any watch you need (inside any controller)
And the most important, from the docs: https://docs.angularjs.org/api/ng/service/$q - "$q.then method returns a new promise which is resolved or rejected via the return value of the successCallback, errorCallback" - this is why each then callback needs a return statement.

Categories