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

运行结果

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值