AngularJS简单入门案例

实现AngularJS实现一个入门级小案例:主要观察双向数据绑定和控制器的作用的

上代码:

<!DOCTYPE html>
<html lang="en" ng-app="HelloApp">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <!-- 使用简易的登录页面分析angular控制器的功能 -->

    <table ng-controller="AppController">
        <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="node_modules/angular/angular.js"></script>
    <script>
        var app = angular.module('HelloApp',[]);
        app.controller('AppController',['$scope',($scope)=>{

            //基本的数据
            $scope.user = {
                username:"",
                password:""
            };
            
            // $scope.message = '';
            //行为数据
            $scope.login = function (){
                console.log($scope.user);
            };

            $scope.message = "请输入用户名";
            //监视
            $scope.$watch('user.username',(now,old)=>{
                if(now){
                    if(now.length<7){
                        $scope.message = "格式不合法";
                    }else{
                        $scope.message = "格式合法";
                    }
                }else{
                    $scope.message = "请输入用户名";
                }
            });
        }]);   
    </script>
</body>
</html>

 

posted on 2018-10-25 15:58  PaulGeorge  阅读(404)  评论(0)    收藏  举报

导航