Angular Factory Variables Won't Update - Instance Gets Old Values
Solution 1:
After hours of research, it appears that the fundamental flaw in what I'm trying to do in the question is this: I'm trying to use a 'singleton' as a 'class'. from the docs:
Note: All services in Angular are singletons. That means that the injector uses each recipe at most once to create the object. The injector then caches the reference for all future needs. http://docs.angularjs.org/guide/providers
My work around was to create the $resource inside a method of a returned object. Here is an example: MyApp.factory('AssetgroupsResource', ['$rootScope', '$resource', function ($rootScope, $resource) {
return {
init: function () {
var accountId = sessionStorage.getItem('engagedAsId');
var apiPath = (accountId != null)
? '/api/account/' + accountId + endpoint
: '/api' + endpoint;
// default params
id:''
},{
// custom actions
});
return Resource;
}
}
}]);
This made it possible to build the object at the right time in the controller:
MyApp.controller('AssetGroupListCtrl', ['Assetgroups', function (Assetgroups) {
varAssetgroups = AssetgroupsResource.init();
// now I can use angular's $resource interface
}]);
Hope this helps someone. (or you'll tell me how this all could've been done in 3 lines!)
Solution 2:
You can always call $scope.$apply();
to force an angular tick.
See a nice tutorial here: http://jimhoskins.com/2012/12/17/angularjs-and-apply.html
Solution 3:
I think $resource
uses promise which might be an issue depending on how you implement your factory in your controller.
$scope.$apply()
can return an error if misused. A better way to make sure angular ticks is $rootScope.$$phase || $rootScope.$apply();
.
Post a Comment for "Angular Factory Variables Won't Update - Instance Gets Old Values"