谈$watch()

主要监听某个值的变化,触发函数。在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

 

转载于:https://my.oschina.net/u/3427060/blog/1524919

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值