1.Angular.Js $scope对象的$watch方法,三个参数
实例1:监听属性
<div class="container" ng-app="myApp" ng-controller="myCtrl"> <form> <div class="form-group"> <label>姓名:</label> <input class="form-control" ng-model="name" /> </div> </form> <div class="alert alert-danger"> 姓名:{{name}} <br /> 修改次数{{updated}} </div> </div> <script type="text/javascript"> //1.使用$watch来监视属性 var app = angular.module('myApp',[]); app.controller('myCtrl',function ($scope) { $scope.name = "张三"; $scope.updated = 0; $scope.$watch('name',function () { $scope.updated++; console.info($scope.updated); }); }); </script>
实例2:获取更新时的新值或旧值
<div class="container" ng-app="myApp" ng-controller="myCtrl"> <form> <div class="form-group"> <label>姓名:</label> <input class="form-control" ng-model="name" /> </div> </form> <div class="alert alert-danger"> 姓名:{{name}} <br /> 修改次数{{updated}} </div> </div> <script type="text/javascript"> //1.使用$watch来监视属性 var app = angular.module('myApp',function (newValue,oldValue) { console.info('new:'+newValue+"----old:"+oldValue); if (newValue == oldValue) return; $scope.updated++; }); }); </script>
实例3:监听自定义对象
<div class="container" ng-app="myApp" ng-controller="myCtrl"> <form> <div class="form-group"> <label>姓名:</label> <input class="form-control" ng-model="user.name" /> </div> </form> <div class="alert alert-danger"> 姓名:{{user.name}} <br /> 修改次数{{updated}} </div> </div> <script type="text/javascript"> //1.使用$watch来监视对象 var app = angular.module('myApp',function ($scope) { $scope.user = { name: '张三' }; $scope.updated = 0; $scope.$watch('user',oldValue) { console.info(newValue); console.info(oldValue); if (newValue == oldValue) return; $scope.updated++; },true); }); </script>
原文链接:https://www.f2er.com/angularjs/149495.html