문제

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.

도움이 되었습니까?

해결책

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top