[英]How to save , display and edit checkbox in angularjs
我已經完成了保存部分。 在下面的代碼中,我演示了如何顯示保存的數據以及如何在單擊“編輯”按鈕時嘗試編輯表單。
這是我的angularjs代碼。
var module=angular.module('myApp',[]);
module.controller('myController',function($scope, $http){
$scope.post.users = [];
$scope.technology = [{
id: 1,
name: 'HTML'
},
{
id: 2,
name: 'PHP'
},
{
id: 3,
name: 'Jquery'
},
{
id: 4,
name: 'AJAX'
},
{
id: 5,
name: 'Angular JS'
}];
// This is the data I fetch and display in form when edit button is clicked
$scope.editUser = function(user){
$scope.empData = {
id: user.id,
firstname : user.firstname,
lastname : user.lastname,
email : user.email,
mobile : user.mobile,
city : user.city,
address : user.address,
experience : user.experience,
designation : user.designation,
//technology : user.technology,
relocate : user.relocate,
salary : user.salary
};
$scope.empData.technology=user.technology;
}
});
這是我的HTML代碼
<body data-ng-app="myApp" data-ng-controller="myController" data-ng-init="init()">
<label>First Name</label>
<input type="text" name="firstname" data-ng-model="empData.firstname" /></br>
<label>Technical Skills</label>
<span ng-repeat="tech in technology">
<input type="checkbox" ng-model="tech.selected" value={{tech.name}} /> {{tech.name}}
</span>
</body>
我已經顯示了數據,但是在編輯中,單擊編輯時如何選中復選框
這樣我顯示數據
<table class="table table-bordered table-hover table-striped">
<thead>
<tr>
<th width="5%">#</th>
<th width="10%">Firstname</th>
<th width="10%">Technical Skills</th>
<th width="10%">Edit</th>
</tr>
</thead>
<tbody>
<tr data-ng-repeat="user in post.users | orderBy : '-id'">
<th scope="row">{{user.id}}</th>
<td> {{user.firstname}} </td>
<td> {{user.technology}} </td>
<td> <span data-ng-click="editUser(user)"> Edit</span></td>
</tr>
</tbody>
</table>
第一:如果您使用的是ng-model
請不要使用value
。 讓角度處理它。
第二:你想做什么? 如果您在單擊復選框時嘗試編輯名稱,請添加另一個帶有文本類型的輸入,將其綁定到name
然后使用ng-disable啟用它。
您正在傳遞ng-model="tech.selected"
但是從$scope.technology
對象中沒有selected
鍵。 首先,您需要像下面這樣添加
$scope.technology = [
{
id: 1,
name: 'HTML',
selected: false
},
{
id: 2,
name: 'PHP',
selected: false
},
{
id: 3,
name: 'Jquery',
selected: false
},
{
id: 4,
name: 'AJAX',
selected: false
},
{
id: 5,
name: 'Angular JS',
selected: false
}];
現在,當您進入編輯頁面時,您必須已經保存了數據,其中tech.selected
的值對於所選復選框為true。 當您使用ng-repeat
迭代數據時,它將顯示為tech.selected = true
選中的復選框
因此,假設您在編輯頁面中具有以下technology
對象
$scope.technology = [
{
id: 1,
name: 'HTML',
selected: true // This will appear checked
},
{
id: 2,
name: 'PHP',
selected: false
},
{
id: 3,
name: 'Jquery',
selected: true // This will appear checked
},
{
id: 4,
name: 'AJAX',
selected: false
},
{
id: 5,
name: 'Angular JS',
selected: true //This will aprear checked
}
];
這個小提琴會更好地向您解釋http://jsfiddle.net/uf4c87t4/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.