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>
运行结果

 
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号