Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS | Plnkr | Watch expression

I am new to angularjs. I am trying to run a sample code of $watch in plnkr, however, I cannot get watch expression triggered. Do I need to trigger digest cycle?

<!DOCTYPE html>
<html>    
  <head>
    <script data-require="[email protected]" data-semver="1.3.8" src="https://code.angularjs.org/1.3.8/angular.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>    
  <body ng-app="funny" ng-controller="funController">
    <input value="{{random.text}}" />
    <div>{{number}}</div>
  </body>    
</html>
<script type="text/javascript>
    var fun = angular.module("funny",[]);
    fun.controller("funController", function($scope) {
      $scope.random = { text : "les c!" };
      $scope.number = Math.random();

      $scope.$watch("random.text", function() {
        $scope.number = Math.random();
      });
    });
</script>

Here is a Plunker link https://plnkr.co/edit/nfkQ6p4nc6MRwThay8Hd?p=preview

like image 587
vibhu Avatar asked Dec 03 '25 10:12

vibhu


1 Answers

Here is the solution:

https://plnkr.co/edit/WpIS2YffE5NabayejJsZ?p=preview

You should use ng-model, because value - isn't angular directive. When you use ng-model, angular automatically runs digest.

<input ng-model="random.text" />

Btw, it's a bad practice to use scope.watch in controller. It's better to set ng-change on input and call controller function.

So here is a cleaner solution https://plnkr.co/edit/iVBWdYhvnfJszNIPteuh?p=preview

like image 198
Kindzoku Avatar answered Dec 04 '25 22:12

Kindzoku



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!