前端學習(1549):$watch監視數據變化

<!DOCTYPE html>
<html lang="en" ng-app="HelloApp">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <table ng-controller="WorldController">
        <tr>
            <td>用戶名</td>
            <td><input type="text" ng-model="user.username"></td>
        </tr>
        <tr>
            <td>密碼</td>
            <td><input type="text" ng-model="user.password"></td>
        </tr>
        <tr>
            <td></td>
            <td><input type="button" ng-click="login()" value="登錄"></td>

        </tr>
        <tr>
            <td></td>
            <td><input type="text" ng-model="user.message"></td>

        </tr>
    </table>
    <script src="./js/Angular.js"></script>
    <!-- 第一個參數是這個模塊的名字 第二個參數是模塊所依賴的模塊 -->
    <script>
        var app = angular.module('HelloApp', []);
        //勇於創建一個控制器
        //創建一個控制器 屬於myApp模塊
        //傳一個參數是獲取 傳兩個參數是創建 會根據參數名稱傳遞對象 所以要保證準確
        app.controller('WorldController', ['$scope', function($scope) {
            //當控制器執行會自動執行的函數
            /*       $scope.username='';
                  $scope.password=''; */
            $scope.user = {
                username: '',
                password: ''
            };
            //行爲數據
            $scope.login = function() {
                //因爲數據的變化是雙向的同步 所以界面上的值變化會同步大屏scope
                console.log($scope.user)
            };
            //監視模型的變化
            $scope.message = '請輸入用戶名'
            $scope.$watch('user.username', function(now, old) {
                console.log('now is' + now);
                console.log('old is' + old);
                if (now) {
                    if (now.length < 7) {
                        $scope.message = '輸入格式不合法'
                    } else {
                        $scope.message = '';
                    }
                } else {
                    $scope.message = '請輸入用戶名';
                }
            })
        }])
    </script>
</body>

</html>

運行結果

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章