Where should you position the $watch function in Angular?

Suppose I have a promise object that my page uses to retrieve data, like so:

promise.then(function (data) {
    $scope.myData = data;
});

In addition to this, I have watches on objects located elsewhere on the page. When it comes to watching data provided by this promise, is it necessary to always include these #watches inside the then callback of the promise?

Answer №1

Watching an object entails subscribing to any changes it undergoes. The function will only be triggered when a change is detected, thus obviating the need for placement within a promise resolve.

Answer №2

Setting up the $watch only once after declaring the variable to receive data is generally how it should be done. Without looking at the specific code, it's hard to say for sure, but setting a $watch every time a promise is returned could cause issues.

The callback function of the $watch receives both the old and new values, allowing you to inspect them and decide what action to take based on those values.

Answer №3

It is advisable to fetch your data from a dedicated service:

app.factory('myService', function($http) {
   var fetchedData = [];
   return {
       getData: function() {
           var promise = $http({method:'GET', url:'/api/someurl' });
           promise.success(function(data) { 
               angular.copy(data, fetchedData);
           });

           return promise;
       },
       data: fetchedData
   }

});

Next, assign the retrieved data to your current scope within your controller

app.controller('ctrl', function($scope, myService) {
    $scope.data = myService.data;
});

Display the data in your HTML, or utilize it inside your directive

<body ng-app="app">
     <ul>
        <li ng-repeat="item in data">{{ item }}</li>
     </ul>
     <my-directive model="data"></my-directive>
</body>

If you opt for a custom directive, make sure to set up your $watch function in the link function of your directive:

app.directive('myDirective', function() { 
     return { 
        restrict: 'E',
        link: function(scope, elem, attr) {
            scope.$watch('data', function(newVal) {
                 ...
            });
        }
     }
});

Keep in mind that $watch handlers should not be part of a promise's callback. It is best to keep them separate to maintain a clear distinction between data retrieval and consumption.

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

Using Node.js and Express to perform a redirect action from an event handler

I am currently developing a nodejs application using express and routing middleware. I am in the process of implementing licensing functionality, where the application periodically checks for expiration. Once the application detects that the license has e ...

Upon initializing mean.io assetmanager, a javascript error is encountered

I am eager to utilize the MEAN.io stack. I completed all the necessary initialization steps such as creating the folder, performing npm install, and obtaining the required libraries. Currently, in server/config/express.js file, I have the following code: ...

Is the detailedDescription missing from the JSON-LD schema crawl?

I am currently utilizing the Google Knowledge Graph Search (kgsearch) API to retrieve Schemas from schema.org. However, I am encountering an issue where some nested elements are not being recognized as JSON or I may be overlooking something... url = "http ...

What is the best way to iterate through an array of objects in React and JavaScript, adding a new property to each object in order to generate a new array

Greetings, I am currently dealing with an array of objects structured as follows: const arr_obj = [ { children: [{}], type: "type1", updated: "somevalue", }, { children: [{}], type: ...

positioned the div within the StickyContainer element to ensure it remains fixed in place

I've been working on making a div sticky in a React project. To achieve this, I added the react-sticky package to my project. I placed the div within the StickyContainer component as per the documentation. Although there are no visible errors, the sti ...

What is the best way to choose the following 3 elements that are siblings of a randomly positioned element?

I need assistance with selecting the next three siblings of a grid of divs on a board. Although I considered using nextUntil(), the issue is that the ids of these siblings are randomly generated upon loading, so they are not fixed. I am unsure how to solve ...

Incorporate Vue3 components and routing within an AngularJS project

Currently, I am in the process of gradually transitioning from AngularJS to Vue3. My plan entails integrating Vue components into certain sections of the project, including routes and server requests. Has anyone had a successful experience incorporating V ...

The layout in Nextjs _app does not stay constant; it refreshes with each page change

After creating a _app.js file: const MyApp = ({Component, pageProps}) => { const getLayout = Component.getLayout || ((page) => <Layout>{page}</Layout>) return getLayout(<Component {...pageProps} />) } export default ...

Troubleshooting the EACCESS error in Node.js on OpenShift

I'm having trouble getting the application to start properly, as I keep receiving an EACCESS error: Error: listen EACCES Below is the code snippet causing the issue: var server_port = process.env.OPENSHIFT_NODEJS_PORT || 8080 var server_ip_address ...

Building nested tree directives with Angular.js using JSON data

Imagine you have an Angular directive that looks like this: <my-tree> <my-tree-item>First</my-tree-item> <my-tree-item>Second</my-tree-item> <my-tree-item>Third</my-tree-item> <my-tree-group> A ...

How can I determine the package version that is being used when requiring it in Node.js?

I am currently working on resolving an issue with a node module that does not have a package.json. The module contains references to cheerio and superagent: var log = console.log.bind(console), superagent = require('superagent'), cheerio ...

Is it possible to conceal specific sections of a timeline depending on the current slide in view?

For my product tour, I've structured a timeline with 4 main sections, each containing 4-5 subsections. Here's how it looks: <ul class="slideshow-timeline"> <li class="active-target-main main-section"><a href="#target">Targe ...

Efficiently converting HTML object data into plain text using RegExr in ReactJS and JavaScript

Is there a way to convert an object in JavaScript/ReactJS into a string? For instance, consider the following object: { article: '<p class="md-block-unstyled">First text...</p><p>Second text></p>' } I am looking to ...

What is the best way to trigger an event in VueJS?

I recently implemented a table using Vuetify in my project. The table is now split into two components - the Table component and the Row component. My challenge is how to handle the same function, this.selected = !this.selected!, when dealing with 2 differ ...

In strict mode, duplicate data properties are not allowed in object literals when using grunt-connect-proxy

I recently started following a tutorial on AngularJS titled "Hands on Angularjs" by Tutsplus. In the tutorial, the instructor uses the grunt-connect-proxy package to redirect ajax requests to a Rails server running on localhost:3000. However, I believe the ...

Most effective method to retrieve yesterday's data

Currently, I'm working on a requirement and I need to validate the logic that I've implemented. Can someone help me with this? The task at hand is to calculate the 1 month, 3 month, and 6 month return percentages of a stock price from the curren ...

Troubleshooting problem with Angular Materials' md-datepicker not displaying correctly in wide browser windows

While using the md-datepicker component in my application, I noticed that it does not display properly on larger browser widths. It only seems to work as expected on small and x-small viewports. Please refer to the attached screenshot for reference. This ...

Is it possible to observe cross-domain Javascript requests in Firebug or any alternative browser extension?

Is there a way to monitor cross-domain JavaScript requests made on a webpage? Is it possible with Firebug or any other plugin? Consider this scenario: If I visit stackoverflow.com and they incorporate an external JavaScript file (such as Google Analytics) ...

What is the proper placement for index.html <head/> class helper functions within a ReactJS Component?

My custom helper functions are stored in a JavaScript file called classie.js: ( function( window ) { 'use strict'; function classReg( className ) { return new RegExp("(^|\\s+)" + className + "(\\s+|$)"); } var hasClass, ...

Dispatching identification to controller after submission

I am encountering an issue with a page that contains the following code: <div class="col-sm-2 displaybutton"> <div data-point-to="displaysHeader"> @using (Html.BeginForm("Administration", "Home", FormMethod.Post)) ...