What steps can I take to prevent my variable from being accessed outside of the angular factory?

In my Angular factory, I have a set of methods for managing a list of objects. One particular method is responsible for making an ajax call to load more items into the list. During this process, I want to display a visual indicator for the "in progress" state of the ajax call (i.e., loading of items). Currently, I am using a simple variable service.isLoading = ... to handle this by setting it to either true or false based on the current state. The challenge with this approach is that the variable becomes accessible outside the factory to any controllers utilizing it.

angular.module('myApp')
    .factory('appFactory', function QuestionsServ(...) {

        var service = {
            list: [],
            isBusy: false
        };

        service.loadItems = function () {
            service.isBusy = true;

            // make ajax call here
            var request = ...

            return request.then( function(res) {
                 service.isBusy = false;
                 ...
            }

        ...

I want to restrict access to this variable within the factory only. Instead of directly manipulating isBusy, I tried implementing a function like below:

        service.checkIsBusy = function () {
            return false;
        }

However, this also causes issues as now the factory itself thinks it is busy. As a result, I cannot access the status of isBusy from within loadItems. What would be the best way to address this dilemma?

Answer №1

To ensure encapsulation, you can declare isBusy as a local var within the module and modify it directly from your code. To make its value accessible to other modules without allowing direct manipulation, create a function that returns it:

angular.module('myApp')
    .factory('appFactory', function QuestionsServ(...) {

        var service = {
            list: []
        };


        // Maintain loading state to indicate if system is busy with ajax data retrieval
        var isBusy = false;

        service.isLoading = function () {
            return isBusy;
        };


        service.loadItems = function () {
            isBusy = true;

            // Perform ajax call here
            var request = ...

            return request.then( function(res) {
                 // Update loading state after successful data retrieval
                 isBusy = false;
                 ...
            }

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

Trouble with filtering data columns in datatable

I have been troubleshooting an issue with my table not filtering properly. Even though data is being retrieved and displayed in the table, the input filter boxes are not working as expected. Despite entering characters into the filter boxes, no actual fi ...

Toggle on and off using a checkbox feature in conjunction with the straightforward form gem

Seeking assistance in toggling an action using a checkbox on a post form. Not well-versed in javascript or JQuery. Struggling with this task while working alone. If anyone can provide guidance, it would be greatly appreciated! Using Rails 4.2.8 an ...

Issue with UI-Grid cellTemplate causing incorrect rendering of directive

It's puzzling for me to notice that my directive is functioning on outdated row entities, failing to catch the updated values as you scroll down or adjust the grid sorting. The first approximately 20 rows display properly, but after that, the directiv ...

Using Vue-Meta for Inline JavaScript in Nuxt.js

Currently, I am working with Nuxt 2.9.2 and attempting to use the innerHTML method to inline a Google Optimize script. However, when I run npm run generate, certain aspects of the code are being transformed even though I have whitelisted innerHTML using __ ...

Error encountered in Laravel 5.2 AJAX request due to a Token Mismatch Exception

I keep receiving a token mismatch exception even though everything seems correct to me. Here is the code from my view: @extends('layouts.master') @section('content') <div class="bg"></div> <div class="login-sec clearfix ...

P5: Exploring the Intersection of Arrays

I am faced with the challenge of extracting values from one array based on indices from another array. I have successfully loaded two text files using loadStrings and stored the data in two separate arrays. The lengths of the two text files are different - ...

Intercepting ajax requests using a Java server

I am currently in the process of developing a Thunderbird extension and I would like to incorporate functionalities from specific Java libraries. However, since the TB extension is coded in pure JavaScript, I am facing challenges in determining the most ef ...

How can one achieve the equivalent of Flask Safe when making an ajax call?

Having trouble replicating equivalent functions in my Ajax call as I can in regular Javascript on my main HTML page. Using Python/Flask at the back-end. Any similar methods to use the {{ variable | safe }} syntax in AJAX for similar results? My code snipp ...

Guide to iterating over an object containing key-value pairs and arrays, then refining the arrays using values found in a different array

Having an object with the following structure : obj = { key: array, key:array} other_array = [value, value, value ...] The objective is to iterate through obj, verify if each value in the array corresponding to each key exists in the other_array, and th ...

Error with HTML5 Audio API: "unable to construct AudioContext due to unavailable audio resources"

Currently, I am attempting to develop a visualization similar to a graphic equalizer for HTML5 audio in Chrome using webkitAudioContext. However, I have encountered some unexpected behavior when trying to switch the audio source, such as playing a differen ...

Navigating through various arrays within objects on a JSON API with JavaScript: A walkthrough

I am currently working on fetching and displaying data from an API. The specific data I am interested in is located within the 'equipments' array. You can see an example of this array in the image linked below: https://i.sstatic.net/QeBhc.jpg M ...

Request was unsuccessful due to error code 400, which indicated a problem with the given MP4 file in the

I've been working on streaming an mp4 file from my computer. I can successfully upload and delete files, but when I click the link after uploading, all I see is {}. Additionally, I'm getting the following errors: GET http://localhost:8000/read/c9 ...

Generate a unique Guid in ASP.NET MVC with the click of a button

When clicking a button, I want to generate a new GUID without reloading the entire view. However, I'm struggling to figure out how to achieve this. This is the function I currently have: Guid.NewGuid() I attempted to do this in JavaScript by adding ...

Achieving the minimum width of a table column in Material-UI

Currently I am in the process of developing a React website with Material-UI. One query that has come up is whether it's feasible to adjust the column width of a table to perfectly fit the data, along with some extra padding on both ends? Outlined be ...

The functionality of ng-switch is not properly executed when attempting to implement conditional statements

I attempted to create a basic switch case based on the value of the data provided. If the value is 1, it should only display "accepted", and so on. However, when the value is either 1 or 2, it displays both "accepted" and "pending," but it works correctly ...

Integrating Angular Dependencies into Your Project?

Currently, I am in the process of learning Angular. Last night, I encountered a problem that caused me quite a few hours of frustration. Although I managed to identify the issue, I am unsure of what led to the problem. Therefore, I would like to present my ...

Start by building a foundation project that incorporates Angular JS and CodeIgniter together

Currently diving into the world of AngularJS and I'm looking to set up a foundation code for building a website with AngularJS and Codeigniter. Does anyone have any sample projects that combine AngularJS and CodeIgniter that they could share? ...

Is there a way to modify page URLs without causing a refresh, regardless of browser?

Despite my extensive searches on various online platforms, including stackoverflow, I have yet to come across a satisfactory answer to my question. While I find the window.history.pushState() and window.history.replaceState() methods quite user-friendly, ...

Discover the position of the element that was clicked within the group of elements sharing the

Here is my HTML code: <input type="button" class="buttonclose marleft fleft clrPric" value="X"> <input type="button" class="buttonclose marleft fleft clrPric" value="X"> <input type="button" class="buttonclose marleft fleft clrPric" value= ...

Refresh the information displayed in the open Google Maps Infowindow

Experimenting with extracting JSON data from a bus tracker website and integrating it into my own version using Google Maps. Although not as visually appealing, I'm struggling to update an infowindow while it remains open. Despite finding some example ...