When using $q.all() to get multiple responses, I get the same values in the response object. I get as many objects back as promises declared, but all the 'name' fields have the same value (the last one, 3).
.controller('myCtrl', function ($scope, $state, $q, myService) {
$scope.myList = [];
$scope.create = function() {
var newObject;
var promises = [];
for(var i = 0; i < 4; i++){
newObject = { name: i };
promises[i] = myService.create(newObject);
}
$q.all(promises).then(
function (response) {
$scope.myList = response;
}
);
};
}
And here's my service:
.service('myService', function ($http, $q, baseURL) {
this.create = function(object) {
var deferred = $q.defer();
//console.log shows that object still has the proper 'name' value
$http.post(url, object).then(
function (response) {
// console.log shows that all response objects have the same 'name' value.
deferred.resolve(response);
}
);
return deferred.promise;
};
}
Any input is appreciated since it's my first approach to promises in Angular.
Solved by moving the newObject declaration inside the loop, as we redeclare the variable, the promise keeps a copy of the previous value to itself.
I'm not really sure what it is you are trying to do, but the way you have your code written, it will always end up with the name of the last one because you are over-writing your promise each time. You would need to do something similar to the following:
var newObject;
var promises = [];
for(var i = 0; i < 4; i++){
newObject = { name: i };
var promise = myService.create(newObject);
promises.push(promise);
}
$q.all(promises).then(
function (response) {
$scope.myList = response;
}
);
};
Related
I created a very simple factory
angular.module('vpmClient')
.factory('DatosFactory', function($http){
var datos = {};
datos.data = [];
datos.getDatos = function(){
$http.post('php/dataHandler.php',{action:"get_datos"}).success(function(data){
datos.data = data;
});
};
datos.getDatos();
return datos;
})
And in the Controller i set the value from "datos.data" to a scope variable
angular.module('vpmClient')
.controller('DatosController', function($http,$scope,DatosFactory){
$scope.datos = DatosFactory.data;
$scope.datoSeleccionado = {};
$scope.getDatos = function(){
console.log(DatosFactory.data);
return DatosFactory.data;
}
$scope.mostrarDato = function(dato){
//$scope.datoSeleccionado = dato;
//Magia
}
});
I need that the value of "scope.datos" updates once the post from the factory ends
Notes: I did a console.log from the factory (inside the success) and it gives me the Object correctly, also, in the controller i created a function to return the factory's value from the browser console and it also works, but when i console.log "scope.datos" it returns an empty object.
Sorry for my bad english
Just return the promise from $http to the controller
angular.module('vpmClient').factory('DatosFactory', function($http){
var datos = {};
datos.data = [];
datos.getDatos = function(){
return $http.post('php/dataHandler.php',{action:"get_datos"});
};
return datos;
})
And in the controller you call the service
angular.module('vpmClient').controller('DatosController', function($http,$scope,DatosFactory){
$scope.datos = DatosFactory.data;
$scope.datoSeleccionado = {};
$scope.getDatos = function(){
DatosFactory.getDatos()
.then(function(httpResponse){
console.log(httpResponse.data);
$scope.datoSeleccionado = httpResponse.data;
})
}
});
You need to use the then keyword:
$scope.getDatos = function() {
DatosFactory.getDatos().then(function(data) {
$scope.datos = data;
});
}
There's quite a few topics out there covering issues with sharing data between controllers, but I havn't found any good answers for my case.
I have one controller that fetches data asynchronous using promise. The controller then makes a copy of the data to work with within that scope. I then have a second controller which I want also want to work on the same copy of data that of the first controller so they both share it.
Here's some code simplified to serve as example:
.controller('firstController', function ($scope, someService){
var vm = this;
someService.getData().then(function(data) {
angular.copy(data, vm.data); //creates a copy and places it on scope
someService.setCurrentData(vm.data)
}
});
.controller('secondController', function ($scope, someService){
var vm = this;
vm.data = someService.getCurrentData(); //Triggers before the setter in firstController
});
.factory('someService', function(fetchService){
var _currentData = {};
var getData = function(){
return fetchService.fetchData().then(function(data) { return data; });
};
var getCurrentData = function(){
return _currentData;
}
var setCurrentData = function(data){
_currentData = data;
}
});
As the getData is async will the setCurrentData be triggered after the getCurrentData, so getCurrentData gives a different object and does not change to the correct one. I know you can solve this with broadcast and watch, but I'm trying to avoid using it if possible.
Refactor your factory to check if the _currentData variable has already been set - then you can simply use callbacks:
app.factory('someService', function(fetchService){
var _currentData = null;
var setCurrentData = function(data){
_currentData = data;
}
var getData = function(callback) {
if (_currentData == null) {
fetchService.fetchData().success(function(data) {
setCurrentData(data);
callback(data);
});
} else {
callback(_currentData);
}
};
/*
var getCurrentData = function(){
return _currentData;
}
*/
});
Now, calling your getData service will check if the data is already got and stored, if so, use that, else go get it!
someService.getData(function(data) {
console.log(data); //yay for persistence!
})
I would solve in this way:
.controller('firstController', function ($scope, $rootScope, someService){
var vm = this;
someService.getData().then(function(data) {
angular.copy(data, vm.data); //creates a copy and places it on scope
someService.setCurrentData(vm.data);
$rootScope.$broadcast('myData:updated');
}
});
.controller('secondController', function ($scope, $rootScope, someService){
var vm = this;
$rootScope.$on('myData:updated', function(event, data) {
vm.data = someService.getCurrentData();
});
});
I have a service in which values can change from outside Angular:
angularApp.service('WebSocketService', function() {
var serviceAlarms = [];
var iteration = 0;
this.renderMessages = function(alarms, socket) {
if (! angular.equals(serviceAlarms, alarms)) {
serviceAlarms = alarms;
iteration++;
}
};
this.getAlarms = function () {
return serviceAlarms;
};
this.iteration = function () {
return iteration;
};
this.socket = initSocketIO(this);
});
The initSocketIO function makes callbacks to this services renderMessages() function and serviceAlarms variable gets changed on a steady basis.
Now i am trying to watch for changes in this service like so:
controllers.controller('overviewController', ['$scope', 'WebSocketService', function ($scope, WebSocketService) {
$scope.$watch(
function () {
return WebSocketService.iteration();
},
function(newValue, oldValue) {
$scope.alarms = WebSocketService.getAlarms();
},
true
);
}]);
to no avail. The second function provided to $watch never gets executed except on controller initialization.
I have tried with and without true as third parameter.
You should use $rootScope.$watch (not $scope.$watch)
I ended up using the solution below since $watch didn't work as excpected.
I refactored the solution to use $rootScope in combination with:
angularApp.run(['$rootScope', function($rootScope){
$rootScope.socket = {};
$rootScope.socket.alarms = [];
$rootScope.socket.faults = [];
$rootScope.socket.renderErrors = function(faults, socket) {
var faultArray = [];
angular.forEach(faults, function(error) {
error.value ? faultArray.push(error) : null;
});
if (! angular.equals($rootScope.socket.faults, faultArray)) {
$rootScope.socket.faults = faultArray;
$rootScope.apply();
}
};
$rootScope.socket.renderMessages = function(alarms, socket) {
if (! angular.equals($rootScope.socket.alarms, alarms)) {
$rootScope.socket.alarms = alarms;
$rootScope.$apply();
}
};
$rootScope.socket.socket = initSocketIO($rootScope.socket);
}]);
Now i have my socket-updated-model in all scopes to use freely in controllers and views.
Controller example:
$scope.acknowledgeAlarm = function(alarm) {
$scope.socket.socket.emit('acknowledgeAlarm', {
hash:alarm.icon.hash,
id:alarm.id
});
};
View example:
<div ng-repeat="alarm in socket.alarms">
{{alarm.name}} {{alarm.icon.progress}}
</div>
So I am having this weird issue where angular.extend is evaluating my parameterless functions. My userData factory is extended from my applicationUserData, but the end result is that my userData object in the userData factory has actual values for needsTraining and showWelcomeText instead of them being functions. The setUserData(appbaseUserData) function still shows up as a function. Any idea why this is?
application.factory('applicationUserData', [function(){
var userData;
return {
setUserData: function(appbaseUserData){
userData = appbaseUserData;
},
needsTraining: function(){
userData.ensureUserDataInitialized();
return userData.needsTraining;
},
showWelcomeText: function(){
userData.ensureUserDataInitialized();
return userData.showWelcomeText;
}
}
}]);
appBaseModule.factory("userData", ["applicationUserData", function(applicationUserData) {
var userData = {},
userDataInitialized = false;
userData.init = function(data) {
applicationUserData.setUserData(userData);
angular.extend(userData, applicationUserData, data);
userDataInitialized = true;
};
....
return userData;
}]);
It's probably not extend that's doing this.
Here is the source for that method in GitHub
function extend(dst) {
var h = dst.$$hashKey;
forEach(arguments, function(obj){
if (obj !== dst) {
forEach(obj, function(value, key){
dst[key] = value;
});
}
});
setHashKey(dst,h);
return dst;
}
What's in data at the time you're calling it? it's possible that it has some value that it's putting in that overwrites your function.
Either way, it's not extend itself. That's a pretty simple function.
I have two controllers on a parallel scope level I need to pass data between:
function TableRowCtrl($scope, $http, sharedProperties) {
console.log(sharedProperties.getProperty());
$scope.items = sharedProperties.getProperty();
}
and
function SideNavCtrl($scope, $http, sharedProperties) {
$scope.customers = undefined;
var temp = "cats";
$http.get('data/customers.json').success(function(data) {
$scope.customers = data;
temp = "dogs";
sharedProperties.setProperty(temp)
});
sharedProperties.setProperty(temp);
console.log(sharedProperties.getProperty());
}
I am trying to use a service to do this (via examples I have seen) :
angular.module('myApp', []).service('sharedProperties', function() {
var property = "Cats";
return {
getProperty: function() {
return property;
},
setProperty: function(value) {
property = value;
}
};
});
However - when I try and set the data in the SideNavCtrl http success function, it does not bubble out - the service still returns 'cats' as its value. From what I have read, services are supposed to be global, and setting data in them should be permanent (as is its purpose). What am I doing wrong, and how can I get data between these two controllers on the same scope?
The problem is your TableRowCtrl saves the result of a function in its scope variable. When the service itself changes, the value in the scope does not because at that point, it's a simple property. You can either expose your service directly in the scope or wrap $scope.items in a function instead:
function TableRowCtrl($scope, $http, sharedProperties) {
$scope.items = function() { return sharedProperties.getProperty(); };
}
// And in your view
{{ items() }}
Or
function TableRowCtrl($scope, $http, sharedProperties) {
$scope.shared = sharedProperties;
}
// And in your view
{{ shared.getProperties() }}
Edit: Simple plunkr here
Edit #2:
If the problem is a binding that isn't updated because of an asynchronous process, you can use $scope.$apply:
$http.get('data/customers.json').success(function(data) {
$scope.customers = data;
temp = "dogs";
sharedProperties.setProperty(temp)
if(!$scope.$$phase)
$scope.$apply();
});
Edit 3:
I've recreated your $http.get and updated the plunkr and it works. Based on what you are showing in your questions, it should work using function instead of regular properties.
#SimomBelanger already identified the problem. I suggest using objects rather than primitives, then you don't need to call functions in your view:
<div ng-controller="TableRowCtrl">items={{items.property}}</div>
<div ng-controller="SideNavCtrl">customers={{customers}}</div>
app.service('sharedProperties', function () {
var obj = {
property: "Cats"
};
return {
getObj: function () {
return obj;
},
setObjProperty: function (value) {
obj.property = value;
}
};
});
function SideNavCtrl($scope, $timeout, sharedProperties) {
$scope.customers = undefined;
var temp = "cats";
$timeout(function () {
$scope.customers = 'some data';
temp = "dogs";
sharedProperties.setObjProperty(temp);
}, 2000);
sharedProperties.setObjProperty(temp);
}
function TableRowCtrl($scope, $http, sharedProperties) {
$scope.items = sharedProperties.getObj();
}
fiddle
In the fiddle I use $timeout to simulate an $http response.
Because getObj() returns a (reference to an) object, updates to that object are automatically picked up by the view.