zoukankan      html  css  js  c++  java
  • angular js一$watch监控属性和对象

    $Watch:(监听一个model,当一个model每次改变时,都会触发第二个函数)

    $watch('watchFn',watchAction,deepWatch)

    watchFn带有Angular 表达式或者函数的字符串,它会返回被监控的数据模型的当前值。

    watchAction: 一个函数function(newValue,oldValue){},当watchFn 发生变化时会被调用

    deepWatch:默认为false,监听数组的某个元素或者对象的属性时设置为true;

    监控一个属性

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8"/>
    </head>
    <body>
    <div  ng-app="myApp" ng-controller="myCtrl">
        <form>
            <div class="form-group">
                <input  ng-model="name" />{{name}}
                <p>改变次数{{count}}</p>
            </div>
        </form>
    </div>
    <script src="http://cdn.static.runoob.com/libs/angular.js/1.4.6/angular.min.js"></script>
    <script type="text/javascript">
       
        var app = angular.module('myApp', []);
        app.controller('myCtrl', function ($scope){
            $scope.name = '橘子';
            $scope.count = 0;
            $scope.$watch('name', function (newValue, oldValue) {
                $scope.count++;
                if($scope.count >5){
                    $scope.name = '苹果';
                }
            });
        });
    </script>
    </body>
    </html>

    监控一个对象(deepWidth为true)

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8"/>
    </head>
    <body>
    <div  ng-app="myApp" ng-controller="myCtrl">
        <form>
            <div class="form-group">
                <input  ng-model="Data.name" />{{Data.name}}
                <p>改变次数{{count}}</p>
            </div>
        </form>
    </div>
    <script src="http://cdn.static.runoob.com/libs/angular.js/1.4.6/angular.min.js"></script>
    <script type="text/javascript">
    
        var app = angular.module('myApp', []);
        app.controller('myCtrl', function ($scope){
            $scope.Data = { name: '橘子' };
            $scope.count = 0;
            $scope.$watch('Data', function (newValue, oldValue) {
                if(newValue == oldValue)
                return;
                $scope.count++;
                if($scope.count >5){
                      $scope.Data.name = '苹果';
                }
            }, true);
        });
    </script>
    </body>
    </html>
  • 相关阅读:
    《一起》Alpha版软件使用说明
    意见评论
    评论总结
    项目评审
    对大神联盟博客的检查结果
    SmartCoder每日站立会议10
    SmartCoder每日站立会议09
    mac php环境启动
    gulp工具rename
    gulp图片压缩
  • 原文地址:https://www.cnblogs.com/Tiboo/p/6753947.html
Copyright © 2011-2022 走看看