$scope.$watch 小例子

<!DOCTYPE html>
<html lang="en" ng-app="HelloApp">
    <head>
        <meta charset="utf-8">
    </head>
    <body>
        <table border="1" ng-controller="WorldController">
            <tr>
                <td>用户名</td>
                <td><input type="text" ng-model="user.username"></td>
            </tr> 
            <tr>
                <td>密码</td>
                <td><input type="password" ng-model="user.password"></td>
            </tr>
            <tr>
                <td></td>
                <td><input type="button" ng-click="login()" value="登录"></td>
            </tr>
            <tr>
                <td></td>
                <td>{{message}}</td>
            </tr>
        </table>
        <script src="bower_components/angular/angular.js"></script>
        <script>
            //创建一个模块
            var app = angular.module('HelloApp',[]);
            //为这个模块创建一个控制器
            app.controller('WorldController',['$scope',function($scope){
                //$scope.username='';
                //$scope.pasword='';
                //数据
                $scope.user = {
                    username:' ',
                    password:''
                };

                //行为数据
                $scope.login = function(){
                    //因为数据的变化是双向的同步,所以界面上的值变化会同步到$scope,user上
                    console.log($scope.user);
                };

                //请输入用户名 输入格式合不合法
                $scope.message = "请输入用户名";
                //$scope.message取决于$scope.user

                //监视模型的变化
                //官方的API中提供了一个$scope.$watch方法

                $scope.$watch('user.username',function(now,old){
                    console.log('now:'+now);
                    if(now){
                        if(now.length<7){
                            $scope.message = '不对';
                        }else{
                            $scope.message= ' ';
                        }
                    }else{
                        $scope.message = '还是不对';
                    }
                },true);

            }]);
        </script>
    </body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值