1

I'm trying to alter the folders variable ( an array) within the return statement of my angular factory but it only seems to work for the create action I wrote. I think I'm not understanding the way variable scope is working in the factory.

this works:

folders.push(response.folder)

but... when I use the underscore.js function _without (that returns an array), it does not alter the folder variable.

folders = _.without(folders, _.findWhere(folders, {id: folder.id })) 

Here is my factory code:

angular.module('cmsApp')
  .factory('Folders', function(Restangular){

    var folders = Restangular.all('folders').getList().$object;

    return {
        get: function(){
          return folders;
        },
        create: function(folderName) {
          folder = { label: folderName };
          folders.post(folder).then(function(response) {
            folders.push(response.folder);
          })
          return folders;
        },
        destroy: function(folder) {
          folders.remove(folder).then(function(){
            folders =  _.without(folders, _.findWhere(folders, {id: folder.id }))
          })
          return folders;
        }
    }
});

The create function returns an updated folders var but the destroy function returns an un-altered folders var.

1 Answer 1

1

_.without returns a new array, see docs, so you are effectively changing where folders is pointing to. However, since you are calling _.without only once the promise resolves, i.e. inside then this change will occur only after you have returned the original folders object so you end up with two references pointing to different arrays.

It's probably best practice to return the actual promise from inside your factory, this way you can reference the correct data once the promise returns.

Sign up to request clarification or add additional context in comments.

1 Comment

Removed the pointer and changed "folders =" to a splice method to alter the actual array. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.