vibhu vibhu - 1 year ago 110
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>
<script data-require="angular.js@1.2.0" data-semver="1.3.8" src=""></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
<body ng-app="funny" ng-controller="funController">
<input value="{{random.text}}" />
<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();

Here is a Plunker link

Answer Source

Here is the solution:

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 in controller. It's better to set ng-change on input and call controller function.

So here is a cleaner solution

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download