Angular factory variable scoping

I am encountering an issue with altering the folders variable (an array) within the return statement of my Angular factory. It seems to work for the create action, but I am having trouble with the scope of the variable in the factory.

This code works:

folders.push(response.folder)

However, when I use the underscore.js function _without (which returns an array), it does not modify the folder variable as expected.

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

Below is the snippet of 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 successfully updates the folders variable, whereas the destroy function does not seem to affect the folders variable as intended.

Answer №1

_.without creates a fresh array, please refer to the documentation. This means that you are essentially modifying the reference of folders. However, since you are executing _.without only after the promise is fulfilled, specifically within then, this modification will take place after returning the original folders object. Consequently, you now have two pointers pointing to distinct arrays.

It is advisable to return the actual promise from your factory function. By doing so, you will be able to access the accurate data once the promise is resolved.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

In order to ensure proper alignment, adjust the width of the select element to match the width of the

Is there a way for the select element to adjust its width based on the length of the selected option? I want the default option value's width to be shorter, but once another option is selected, I'd like the select element to resize itself so that ...

I'm curious about the meaning of "!" in pseudo-code. I understand that it represents factorial, but I'm unsure of how to properly interpret it

Can someone explain the meaning of ! in pseudo-code to me? I understand that it represents factorial, but for some reason I am having trouble translating it. For example: I came across this code snippet: if (operation!= ’B’ OR operation != ’D’ O ...

The absence of HttpOnly Secure Cookies being transmitted

Here we go again, another inquiry regarding httpOnly Cookies. Seems like many others are facing the same predicament as me. Even though I receive the cookie from the server, it doesn't accompany other requests. I have mysite.example.com in angularj ...

An issue occurred while attempting to execute a function in AngularJS

Currently, I am in the process of developing a cross-platform application using AngularJS, Monaca, and Onsen UI. My current challenge involves calling a function in my controller from an ng-click() event on my view. However, upon clicking the button that ...

I'm encountering an undefined JavaScript variable, how should I proceed?

$(function(){ //Location was "set". Perform actions. $("#geocodesubmit").click(function(){ var geocoder = new google.maps.Geocoder(); geocoder.geocode( { 'address': address}, function(results, status) { if (status ...

Unable to resize static and draggable elements simultaneously

Observe this fiddle to see the demonstration: DEMO If you are interested in the resizing of white divs, check out this link: Resizing of White divs The draggable divs are represented by red while the static divs are shown in white and located in droppabl ...

Emails can be sent through a form without the need for refreshing

I am currently working on a webpage that utilizes parallax scrolling, and the contact box is located in the last section. However, I encountered an issue where using a simple HTML + PHP contact box would cause the page to refresh back to the first section ...

Display a modal before leaving the page?

I need to display a modal message when a user navigates away from the page, triggered by a successful AJAX call. The issue is that if the message loads too quickly, the user may not have enough time to read it before being directed to another page. This is ...

Modify content or display picture within accordion panel based on its identifier

In my view, I have a model representing a list of items. Each item has a unique ID, which is included in the H2 header tag. The details of each item are displayed in a div below the header. Initially, there is an image within the header that is set to disp ...

Tips for delivering a variable to a React Native Stylesheet

Is there a way to pass a variable to the "shadowColor" property in my stylesheet from an array declared in the code above? I keep encountering a "Can't find name" error. Attempting to use a template literal has not resolved the issue. Any assistance w ...

Issue with Vue.js - Double curly braces not rendering data on the page

I've recently delved into the world of vue.js Strangely enough, the double curly braces syntax doesn't seem to be rendering for me. However, when I utilize the v-text directive, everything falls into place. Here's a snippet of my code: HTM ...

Filtering URLs using Firefox extension

As the page loads, multiple HTTP requests are made for the document and its dependencies. I am looking to intercept these requests, extract the target URL, and stop the request from being sent if a specific condition is met. Additionally, plugins may als ...

The attempt to decode the string from POST using json_decode failed due to a hang-up in

I'm currently learning about PHP, JSON, and JavaScript. I am facing an issue with using the json_decode function in PHP after receiving a JSON string from JavaScript. I am able to save the JSON string to a file without any problem, but when I try to ...

Error: Unable to access the 'create' property of an undefined object while utilizing sequelize to register a user and add an entry

Whenever I try to execute this controller, an issue arises indicating a problem with the recognition of the .create method from the model. What is the correct way to import Sequelize in order to utilize it effectively? const db = require("../Models/m_use ...

Having trouble loading AngularJS 2 router

I'm encountering an issue with my Angular 2 project. Directory : - project - dev - api - res - config - script - js - components - blog.components.js ...

What is the solution to preventing Angular 1.3 ngMessages from affecting the size of my form?

Hey there, I'm diving into front-end design for the first time. My issue is with a form that I want to use ng-messages for validation error messages. Currently, my form's size changes depending on whether there are errors displayed or not, and it ...

Is there a way to conceal a slice of a pie chart in HighCharts without excluding it from the legend display?

I've been searching everywhere for a solution to this issue, but I just can't seem to pinpoint where I'm going wrong. My goal is to initiate a pie chart using HighCharts with specific slices hidden as if they were "clicked" off in the legen ...

Collaborate and apply coding principles across both Android and web platforms

Currently, I am developing a web version for my Android app. Within the app, there are numerous utility files such as a class that formats strings in a specific manner. I am wondering if there is a way to write this functionality once and use it on both ...

The Vue component fails to respond to updates in plugin data

I am currently working on implementing a feature where a component reacts to data changes in a custom Vue plugin. To achieve this, the plugin creates a new instance of a Vue object in its constructor: this._vm = new Vue({ data: { obj: null, stat ...

What is the method to obtain the content height of individual pages in Android, with or without the use of JavaScript?

I am facing an issue while trying to retrieve the content height of each webpage consecutively. When I load pages separately, I can successfully get the height of each page. However, when I attempt to fetch the content height continuously for webpages in a ...