<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="abc">
<p>Input something in the input box:</p>
<p>Name : <input type="text" ng-model="name" placeholder="Enter name here"></p>
<h1>Hello {{name}}</h1>
</div>
<script>
var app=angular.module('myApp',[]);
app.controller('abc',
['$scope',function($scope) {
$scope.name='xyz';
var count=-1;
$scope.$watch('name',function(nv,ov){
console.log('OV',ov);
console.log('NV',nv);
$scope.name=nv;
count++;
console.log(count);
})
}]
)
</script>
</body>
</html>
这里$ watch只运行一次而不是最少两次。如果我将ov
分配给$scope.name
$watch
正在运行11次,在这种情况下,名称的值不应该更改。
答案 0 :(得分:0)
尝试下面的代码,下面一个显示正确的o / p对我来说可能是你想要同一个
<script>
var app=angular.module('myApp',[]);
app.controller('abc',['$scope',function($scope){
$scope.name='xyz';
var count=-1;
$scope.$watch('name',function(data){
console.log('data', data);
$scope.name=data;
count++;
console.log(count);
})
}])
</script>