我有一个编辑表单,其中包含“项目”的模型数据。该项目具有分配给它的一组用户,并且控制器具有可分配的整个用户列表的另一个阵列。表单当前列出了所有可用用户,我想要做的是勾选已分配给项目的用户,如果用户修改了已检查/未检查项目列表,则更新相关的project.users属性。
代码位于:http://plnkr.co/edit/e2Rc45mgWDkgdHxz1bz0?p=preview
控制器
angular.module('app', [])
.controller('ProjectsController', ['$scope', function($scope) {
$scope.project = {"projectID":"26","projectName":"project one","projectDescription":"blah",
"users":[{"userFullName":"Ian","userID":"2"},
{"userFullName":"Kevin","userID":"33"},
{"userFullName":"Peter","userID":"32"}]
};
$scope.collaborators = [
{"userID":"2","userFullName":"Ian"},
{"userID":"33","userFullName":"Kevin"},
{"userID":"32","userFullName":"Peter"},
{"userID":"31","userFullName":"Tom"}
];
$scope.updateProject = function(project){
console.log(project);
}
}]);
表格
<form name="editProjectForm" novalidate ng-submit="updateProject(project)" >
<label>Name</label><BR>
<input type="text" ng-model="project.projectName" class="form-control" required><BR><BR>
<label>Description</label><BR>
<textarea ng-model="project.projectDescription" class="form-control" required></textarea>
<br>
<label>Assigned to work on project</label><BR>
<label ng-repeat="collaborator in collaborators">
<input type="checkbox" ng-model="???" /> {{collaborator.userFullName}}
</label>
<BR> <BR>
<input type="submit" value="Update project details" class="btn btn-primary">
</form>
答案 0 :(得分:1)
您可以在控制器中创建一个$scope.checked
对象,该对象将扫描您的项目用户与协作者用户,并根据该对象形成布尔值。
<强> JS 强>
// Checked model will not interfere with existing collaborators
// or project models. Simply a glue between controller and view.
$scope.checked = {};
// Add all possible collaborators to the checked model
angular.forEach( $scope.collaborators, function( item )
{
$scope.checked[ item.userID ] = false;
});
// Auto-check any users already assigned to the project
angular.forEach( $scope.project.users, function( item )
{
$scope.checked[ item.userID ] = true;
});
<强> HTML 强>
<label ng-repeat="collaborator in collaborators">
<input type="checkbox" ng-model="checked[collaborator.userID]" /> {{collaborator.userFullName}}
</label>
答案 1 :(得分:0)
看看Checklist-model。它为复选框列表添加了checklist-model
和checklist-value
指令,我认为这正是您所需要的。
在您的示例中使用它可能看起来像这样:
<label ng-repeat="collaborator in collaborators">
<input type="checkbox"
checklist-model="project.users"
checklist-value="collaborator" /> {{collaborator.userFullName}}
</label>
它具有MIT许可证,因此在商业项目中使用它不应该是一个问题。