9.11监听watch

监听自带的angular属性 ng-model

{{age}}
 angular.module('zfMod', [])
    .controller('WatchCtrl',function($scope){
        $scope.age = 100;
       $scope.$watch('age',function(newVal, oldVal){
            console.log(newVal, oldVal);
      })

        console.log($scope);
    })

自己实现数据绑定

{{age}}
 angular.module('zfMod', [])
    .controller('WatchCtrl',function($scope,$interval){
        $scope.age = 100;
        $interval(function(){
                $scope.age = parseInt($scope.age)+1;
        },1000);

        console.log($scope);
    }).directive('zfModel',function($timeout){
        return {
            link:function(scope,element,attrs){
                element.on('keypress',function(){
                    console.log('keypress',element.val());
                    //强制观察者去对比模型是否改动,监听必须走这个方法,监听才会生效{{age}}才会去更新自己状态
                    scope.$apply(function(){
                        scope.age = element.val();
                    });
                    /*$timeout(function(){
                        scope.age = element.val();
                    },0);*/

                });
                //模型变化时执行回调,修改视图的值
                var watcher = scope.$watch('age',function(newVal,oldVal){
                    console.log(newVal,oldVal);
                    if(newVal != oldVal){
                        element.val(scope.age);
                    }
                })
                console.log('scope',scope);
            }
        }
    })

你可能感兴趣的:(9.11监听watch)