Is there a way to manage the iteration of $scope.$watch?

I'm currently facing an issue with controlling the $scope.$watch function in my code. It seems to be causing an infinite loop during iteration.

$scope.$watch('dashboards', function(newVal, oldVal) {
        if (newVal !== oldVal) {
            $scope.dashboard = $localStorage.sample;
            $scope.dashboards['1'].id = $scope.dashboards[1].id + 1;
            $localStorage.sample = $scope.dashboards[1];
            console.log('newval: '+$scope.dashboards['1'].id);
        } else {
            $scope.$storage = $localStorage;
            $localStorage.sample = $scope.dashboards[1];
            $scope.dashboard = $localStorage.sample;
            $scope.dashboards['1'].id = $scope.dashboards[1].id.length + 1;
            $localStorage.sample = $scope.dashboards[1];
            console.log('oldval: '+$scope.dashboards['1'].id);
        }
    }, true);
    

Below is the content of my scope.dashboards:

$scope.dashboards = {
        '1' : {
            id : '1',
            widgets : [{
                code : "bla1.html",
                col : 0,
                row : 0,
                sizeY : 1,
                sizeX : 2,
                title : "Bla1"
            }, {
                code : "bla2.html",
                col : 2,
                row : 0,
                sizeY : 2,
                sizeX : 2,
                title : "Bla2"
            }, {
                code : "bla3.html",
                col : 0,
                row : 4,
                sizeY : 1.5,
                sizeX : 2,
                title : "Bla3"
            }
        }
    

I am aiming to update the localStorage with a new ID every time there is a change in widget position within $scope.dashboards. This will help in preserving the widget positions even when the browser is closed or refreshed. Any suggestions on how to approach this issue would be greatly appreciated. Thank you!

Answer №1

The main issue arises from altering the value being watched in the $watcher (of $scope.dashboards), leading to an endless loop.

To resolve this, you can either refrain from using the $watch to update $scope.dashboards.id and instead identify the actual trigger for the widget changes. (On a side note, the usage of the property id might be confusing, consider changing it to "version" or something similar)

Alternatively, you can opt to only $watch the widgets property instead of delving into a deep-watch of dashboards.

$scope.$watch("dashboards['1'].widgets", function(newVal, oldVal){
 ...
}, true);

Answer №2

Here's a suggested approach you can take:

let changesOngoing = false;
$scope.$watch('dashboards', function(newVal, oldVal) {
  if (!changesOngoing) {
    changesOngoing = true;
    // apply modifications to dashboards
  }
  $timeout(function() {
    changesOngoing = false;
  }, 0);
});

If you anticipate multiple modifications to the dashboard in the same cycle, there may be unexpected issues. However, if changes are expected to occur once per cycle (e.g., when a button is clicked), this method should suffice.

That being said, the structure of your code is a bit unusual. Consider refactoring to avoid observing and altering the same variable. For instance, monitoring a different object and keeping track of the number of modifications on a separate variable could prevent the infinite loop scenario.

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

I am unable to retrieve information from Firebase in Vue

Currently, I am following a tutorial on YouTube to enhance my knowledge about storing data in Firebase and then utilizing it in a Vue application. (You can watch the tutorial at this link: https://www.youtube.com/watch?v=Htt8AKeF1Kw, you will encounter the ...

Strikeout list on click of a mouse

Is there a way to apply strikethrough formatting to text with just a mouse click? The CSS for lists is beyond the form field margin. I've tried multiple methods without success. No matter how many times I change the code, I can't seem to get it r ...

AngularJS Tutorial: Implementing Pagination on Separate Routes

For quite some time now, I've been facing an issue with pagination on my home page. I successfully implemented pagination and have a search input that returns products based on user search. In my controller, I am routing the data to different URLs and ...

What is the process for importing specific modules from jQuery?

When working with webpack or browserify, what is the specific procedure required to import only the essential modules from jQuery as mentioned here? import {core, dimensions} from 'jquery' Unfortunately, this approach does not seem to be effect ...

Showing a DIV multiple times with an additional text field in HTML and JS

As someone new to development, I am facing a requirement where I need to create a form with a dynamic field that can be added or removed using buttons. When the user clicks on the Add button, another field should appear, and when they click on Remove, the ...

Verify if a personalized angular directive is able to display or conceal an element

I have a custom directive that toggles the visibility of an element based on the value of another service. I attempted to write a test to verify if the directive functions as intended. Initially, I used the ":visible" selector in my test, but it consistent ...

An effective method for modifying the active class on an li element in jQuery and ensuring that the user is directed to the desired page upon clicking the li element

I am facing an issue with my script tag. When I click on the links test.php or test2.php, the active class changes from index.php to the respective file but I am not redirected to the clicked page. I have tried solutions from various sources but none of th ...

Updating React state via child components

Encountering a strange issue while working on a project, I managed to replicate it in this jsfiddle. The parent component's state seems to be affected when the child component updates its state. Any insights on what might be causing this? Here is the ...

Sending the parameter with the URL and receiving the response in return

Can the result be retrieved by calling a URL and sending specific parameters with it? For instance, if I pass two numbers along with the URL, can I receive the sum in return? The addition operation is carried out on the page being called upon. ...

Is it possible that ng-click gets filtered out by Angular's ng-bind-html?

I am currently working with HTML data that I am importing from a JSON file. To display this HTML data in my application, I am utilizing ngSanitize along with ng-bind-html. My goal is to transform any standard links in the JSON blob from: <a href="so ...

Tips for removing the query string when invoking $location.path() in angularjs?

Upon logging in, I utilize the command $location.path('/dashboard') to navigate to the dashboard page. Angularjs automatically appends the current query string, resulting in the URL displayed in the browser as www.myweb.com/dashboard?urlredirect= ...

After a successful login, learn how to implement a bottom tab menu in React Native

I'm diving into the world of react-native and finding myself a bit lost when it comes to routing and navigation. I have 4 screens - Login, Register, Home, and Links. The Register and Login screens are all set up, with the ability to navigate back usin ...

Looking to retrieve the mouse coordinates using JavaScript

How can I use JavaScript to track the mouse position on a canvas? Upon visiting this page: http://billmill.org/static/canvastutorial/mouse.html They provide this code snippet: function initializeMouse() { canvasMinimumX = $("#canvas").offset().left; ...

Determine the altered props within the componentWillReceiveProps lifecycle method

During the process of debugging React code, it is common to come across situations where componentWillReceiveProps gets triggered unexpectedly, but identifying which prop change is causing this issue can be challenging. Is there a method available to easi ...

changing font size on a mobile-friendly site using javascript

Currently, I am designing a responsive webpage utilizing Bootstrap framework. Situated in the center of the screen is a text that reads: <p id="entershop" ><a class=no-deco href="shop.html">enter shop</a></p> Within the Bootstra ...

How can I retrieve the width of a responsive React element during its initial rendering phase?

In my React project, there is a component called ResultList which is used to display products in a gallery format. The challenge I'm facing is determining the appropriate number of products to show per row based on the available width for the ResultL ...

Retrieving and storing data using jQuery's AJAX caching feature

When utilizing jQuery's $.ajax() method to perform an XHR based HTTP GET request to obtain a partial of HTML from a Ruby on Rails website, I encounter an issue. Specifically, every time a user clicks on tabbed navigation, I refresh an HTML table with ...

Choosing options from an API response in a REACT-JS application

I have a Select Component in my application and I want it to automatically show the selected data once the response is received. import Select from "react-select"; <Select menuPlacement="auto" menuPosition="fixed" ...

Menu Toggle with Bootstrap 3

I have implemented two Bootstrap 3 navigation menus on a single page. One menu works fine when the toggle button is activated for responsiveness, but the other one doesn't work as expected. How can I resolve this issue? Below are the code snippets fo ...

Creating an Active Link in Bootstrap 5.0 (Beta 3) Navbar Using JavaScript

I am currently working with Bootstrap 5 (Beta 3 - no JQuery) on a static website, and I am facing the challenge of making a navbar link appear active. I prefer to achieve this using JavaScript instead of creating a separate navbar for each page. For instan ...