用户编辑新建_AngularJS实现

时间:2023-11-12 19:53:26

实现思路:

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

 <!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
<script src="http://apps.bdimg.com/libs/angular.js/1.3.9/angular.min.js"></script>
</head> <body ng-app="myApp" ng-controller="userCtl">
<table>
<tr>
<TD></TD><td>名</td><td>姓</td>
</tr>
<tr ng-repeat="user in users">
<TD><button type="button" ng-click="editUser(user.id)">编辑</button></TD><td>{{user.firstname}}</td><td>{{user.lastname}}</td>
</tr>
</table>
<input type="button" value="创建新用户" ng-click="editUser('new')">
<h3 ng-show="edit">新建用户</h3>
<h3 ng-hide="edit">编辑用户</h3>
<form>
firstname:<input type="text" name="firstnam" ng-model="firstname" ng-disabled="!edit"><br>
lastname :<input type="text" name="lastname" ng-model="lastname" ng-disabled="!edit"><br>
密 码:<input type="password" name="passwd1" ng-model="passwd1"><br>
重 复 密 码:<input type="password" name="passwd2" ng-model="passwd2" ><br>
<button ng-disabled="error || incomplete">提交</button>
</form>
<script>
var app=angular.module("myApp",[]);
app.controller("userCtl",function($scope){
$scope.firstname='';
$scope.lastname='';
$scope.edit=true;
$scope.users=[{id:1,firstname:'john',lastname:'cena'},{id:2,firstname:'jeff',lastname:'chen'},{id:3,firstname:'bill',lastname:'gates'},];
$scope.editUser = function(id){
if(id == 'new'){
$scope.edit=true;
$scope.firstname='';
$scope.lastname=''; } else {
$scope.edit = false;
$scope.firstname=$scope.users[id-1].firstname;
$scope.lastname=$scope.users[id-1].lastname;
$scope.passwd1='';
$scope.passwd2='';
}
}; $scope.error = false;
$scope.incomplete = false;
$scope.$watch("firstname",function(){ $scope.test(); });
$scope.$watch("lastname",function(){ $scope.test(); });
$scope.$watch("passwd1",function(){ $scope.test(); });
$scope.$watch("passwd2",function(){ $scope.test(); });
$scope.test = function(){
if($scope.passwd1 !== $scope.passwd2) {
$scope.error = true;
}
else {
$scope.error = false;
}
$scope.incomplete = false;
//新建用户状态,而且四个属性只要有一个没有值,就是未完成状态
if( $scope.edit && ( !$scope.firstname.length || !$scope.lastname.length || !$scope.passwd1.length || !$scope.passwd2.length )) {
$scope.incomplete = true;
}
};
});
</script>
</body>
</html>