主要监听某个值的变化,触发函数。在controller:$scope.$watch() directive:$scope.$watch()
apply()——>digest()——>watch()
$watch(watchFn,watchAction,deepWatch)
watchFn:angular表达式或函数的字符串被监听‘字符串’
watchAction(newValue,oldValue,scope):watchFn发生变化会被调用 触发函数
deepWatch:可选的布尔值命令检查被监控的对象的每个属性是否发生变化 布尔值
<p>{{message}}</p><input ng-model="message" />
link:function(scope, element, attrs){
scope.$watch('message', function(){
console.log("dd")
})
控制器里面:
<body ng-controller="MainCtrl">
<input ng-model="name" />
Name updated: {{updated}} times.
</body>
app = angular.module('app', []);
app.controller('MainCtrl', function($scope) {
$scope.name = "Angular";
$scope.updated = -1;
$scope.$watch('name', function() {
$scope.updated++;
});
});
还回参数里面俩参数newValue, oldValue,当监听对象是不是字符串,如下面这样需要加 true
<body ng-controller="MainCtrl">
<input ng-model="user.name" />
Name updated: {{updated}} times.
</body>
app = angular.module('app', []);
app.controller('MainCtrl', function($scope) {
$scope.user = { name: "Fox" };
$scope.updated = 0;
$scope.$watch('user', function(newValue, oldValue) {
if (newValue === oldValue) { return; }
$scope.updated++;
}, true);
});
项目案例:
var uploadFile = (['$stateParams', 'mzServer', function ($stateParams, mzServer) {
return {
restrict: 'EA',
require: "ngModel",
link: function (scope, element, attrs, ngModelController) {
scope.$watch(attrs.ngModel, function (data) {
if (attrs.required) {
ngModelController.$setValidity('uploadFile', false);
}
if (mzServer.isEmptyOrNull(data) || angular.isUndefined(data)) {
$(element).fileinput('refresh', { initialPreview: ["/images/no_img.jpg"], initialPreviewAsData: true, });
}
else {
var arrimg = [];
arrimg.push(attrs.readimg +"/"+ data);
$(element).fileinput('refresh', { initialPreview: arrimg, initialPreviewAsData: true, });
if ($stateParams.OpType.toLowerCase() == "query") {
$('.file-caption-main').hide();
}
ngModelController.$setValidity('uploadFile', true);
}
});
参考:http://xlows.blog.51cto.com/5380484/1425445