Pregunta

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.

¿Fue útil?

Solución

_.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.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top