Home > Software engineering >  Trying to understand Angular context & Watchers
Trying to understand Angular context & Watchers

Time:12-13

I read like AngularJS has a context where it has deployed watchers and digestive loop. So if any variable is updated from either front-end or backend-end, these above-mentioned components will help to make sure all the respective fields where this variable is involved will be updated.

So I thought of testing this, so created a sample multiple by 2 like below

<!DOCTYPE html>
<html ng-app="myapp">
  <head>
    <title>Parcel Sandbox</title>
    <meta charset="UTF-8" />
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.js"></script>
  </head>

  <body>
    <div id="app"></div>
    <script>
      
    </script>
    <div  ng-controller="maincontroller">
      <label id="input_value">Please enter number </label>
      <input type="text" id="input_value" ng-model="number" />

      <p>You have entered : {{ number }}</p>
      <p>
      Multiplied by 2 : {{ multipleBy2 }}
      </p>
      
    </div>

    <script src="src/index.js"></script>
  </body>
</html>

and my index.js code is as below

var myapp = angular.module("myapp", []);
      var maincontroller = function ($scope) {
        $scope.number = "";
        
        $scope.multipleBy2 = $scope.number * 2; // this is returning zero at the beginning of the page.
        
      };
      myapp.controller("maincontroller", maincontroller);

is it wrong if I expect that, the moment number input field received 2, I should see Multiplied by 2 : as 4 ?

Am I missing anything here?

CodePudding user response:

In order for this to work as you're expecting out of the box, AngularJS would need to do one of two things:

  1. Reprocess everything on every change, which would be a performance nightmare, or
  2. Be smart enough to know when certain scope properties are dependent on the value of other scope properties and only reprocess those relevant properties, which would be massively complex.

The easy way to render the result of something that always needs to run fresh is to make it the result of a function instead of a property.

$scope.multipleBy2 = () => $scope.number * 2;

While AngularJS expressions bound to function results will always re-run on a digest loop, it won't actually re-render the DOM of the corresponding element unless the value changes in between digests, so thankfully there is some optimization that takes place.

As a best practice, these functions should should not mutate the state of the $scope when run, otherwise you could get into infinite digest loop issues.

$scope.multipleBy2 = () => $scope.number   * 2;
// infinite $digest loop error
  • Related