vibhu vibhu - 3 months ago 21
AngularJS Question

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="angular.js@1.2.0" 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

Answer

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