<!DOCTYPE html>
<html ng-app="myApp">
<head>
<meta charset="UTF-8">
<title>angular demo</title>
<script src="../bower_components/angular/angular.min.js"></script>
</head>
<body>
<div ng-controller="containerCtrl">
<p>在输入框中输入</p>
<p>姓名:<input type="text" ng-model="name"></p>
<p >{{name}}</p>
<p >{{sex}}</p>
</div>
<script>
var app = angular.module('myApp',[]);
app.controller('containerCtrl',function($scope){
/*$scope.$watch($scope.name,function(name,oldname,scope){
debugger;
if (oldname=='123') {
scope.sex='女'
} else {
scope.sex='男'
}
});*/
$scope.sex = '男'
$scope.$watch($scope.sex,function(newValue,oldValue){
// var name =$scope.name;
console.log(newValue);
$scope.sex = newValue>18 ? '女' : '男';
})
});
</script>
</body>
</html>
这个时候$watch内部只执行一次console.log(newValue);
翻文档例子,整了半天才发现$watch第一个传参必须得是一个回调函数或方法
改之后:
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<meta charset="UTF-8">
<title>angular demo</title>
<script src="../bower_components/angular/angular.min.js"></script>
</head>
<body>
<div ng-controller="containerCtrl">
<p>在输入框中输入</p>
<p>姓名:<input type="text" ng-model="name"></p>
<p >{{name}}</p>
<p >{{sex}}</p>
</div>
<script>
var app = angular.module('myApp',[]);
app.controller('containerCtrl',function($scope){
/*$scope.$watch($scope.name,function(name,oldname,scope){
debugger;
if (oldname=='123') {
scope.sex='女'
} else {
scope.sex='男'
}
});*/
$scope.getSex = function(){
return $scope.name
};
$scope.$watch($scope.getSex,function(newValue,oldValue){
// var name =$scope.name;
console.log(newValue);
$scope.sex = newValue>18 ? '女' : '男';
})
});
</script>
</body>
</html>