用户编辑新建_AngularJS实现

实现思路:

分步骤完成开发,逐渐添加功能:
1.实现输出users对象。
2.实现点击“编辑”按钮,在表单中显示firstname和lastname,并不可修改。
3.实现“新建用户”和“编辑用户”的切换。
4.实现“创建新用户”按钮。
5.实现“验证”部分。

 1 <!doctype html>
 2 <html>
 3 <head>
 4 <meta charset="utf-8">
 5 <title>无标题文档</title>
 6 <script src="http://apps.bdimg.com/libs/angular.js/1.3.9/angular.min.js"></script>
 7 </head>
 8 
 9 <body ng-app="myApp" ng-controller="userCtl">
10 <table>
11 <tr>
12 <TD></TD><td></td><td></td>
13 </tr>
14 <tr ng-repeat="user in users">
15 <TD><button type="button" ng-click="editUser(user.id)">编辑</button></TD><td>{{user.firstname}}</td><td>{{user.lastname}}</td>
16 </tr>
17 </table>
18 <input type="button" value="创建新用户" ng-click="editUser('new')">
19 <h3 ng-show="edit">新建用户</h3>
20 <h3 ng-hide="edit">编辑用户</h3>
21 <form>
22 firstname:<input type="text" name="firstnam" ng-model="firstname" ng-disabled="!edit"><br>
23 lastname :<input type="text" name="lastname" ng-model="lastname" ng-disabled="!edit"><br>
24 密      码:<input type="password" name="passwd1" ng-model="passwd1"><br>
25 重 复 密 码:<input type="password" name="passwd2" ng-model="passwd2" ><br>
26 <button ng-disabled="error || incomplete">提交</button>
27 </form>
28 <script>
29 var app=angular.module("myApp",[]);
30 app.controller("userCtl",function($scope){
31     $scope.firstname='';
32     $scope.lastname='';
33     $scope.edit=true;
34     $scope.users=[{id:1,firstname:'john',lastname:'cena'},{id:2,firstname:'jeff',lastname:'chen'},{id:3,firstname:'bill',lastname:'gates'},];
35     $scope.editUser = function(id){
36         if(id == 'new'){
37             $scope.edit=true;
38             $scope.firstname='';
39             $scope.lastname='';
40             
41         } else {
42             $scope.edit = false;
43             $scope.firstname=$scope.users[id-1].firstname;
44             $scope.lastname=$scope.users[id-1].lastname;
45             $scope.passwd1='';
46             $scope.passwd2='';
47         }
48     };
49     
50     $scope.error = false;
51     $scope.incomplete = false;
52     $scope.$watch("firstname",function(){ $scope.test(); });
53     $scope.$watch("lastname",function(){ $scope.test(); });
54     $scope.$watch("passwd1",function(){ $scope.test(); });
55     $scope.$watch("passwd2",function(){ $scope.test(); });
56     $scope.test = function(){
57         if($scope.passwd1 !== $scope.passwd2) {
58             $scope.error = true;
59         }
60         else {
61             $scope.error = false;
62         }
63         $scope.incomplete = false;
64         //新建用户状态,而且四个属性只要有一个没有值,就是未完成状态
65         if( $scope.edit && ( !$scope.firstname.length || !$scope.lastname.length || !$scope.passwd1.length || !$scope.passwd2.length )) {
66             $scope.incomplete = true;
67         }
68     };
69 });
70 </script>
71 </body>
72 </html>
原文地址:https://www.cnblogs.com/cag2050/p/5111473.html