angular js一$watch監控屬性和對象

來源:互聯網
上載者:User

標籤:監控   ng-model   type   span   head   html   char   min   java   

$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>

 

angular js一$watch監控屬性和對象

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.