Skip to content Skip to sidebar Skip to footer

Angular Factory Variables Won't Update - Instance Gets Old Values

I have a resource factory that builds objects for accessing our API. I use an environment variable to determine the base part of the URL - whether or not to include 'account/id' pa

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:

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"