2016-12-05 87 views
0

所以我是AngularJS的新手,我期待创建好的代码,因为我的应用程序正在扩展。AngularJS - 表单良好实践

现在,我列出了我从API获得的权限,然后我需要使用复选框列出它们的列表,然后用户将从列表中选择/取消选择,然后提交形成。

那么我该如何实现呢?每个复选框的ng模型应该是什么?我应该创建一个表单中的所有值为false吗?

这里是我的控制器代码现在:

function Controller(Competence) { 

    var vm = this; 

    vm.competences = []; 

    function initController() { 
     Competence.getAll() 
      .then(function(data) { 
       vm.competences = data; 
     }); 
    } 

    initController(); 

} 

这是我的看法代码:

<table> 
    <thead> 
     <tr> 
      <th width="90%">Competence</th> 
      <th width="10%">Select</th> 
     </tr> 
    </thead> 
    <tbody> 
     <tr ng-repeat="competence in vm.competences"> 
      <td>{{ competence.name }}</td> 
      <td><input type="checkbox"></td> 
     </tr> 
    </tbody> 
</table> 

回答

1

到目前为止,你的代码看起来不错。要设置复选框值,只需添加ng-model="competence.selected"到每个复选框输入元素是这样的:

<input type="checkbox" ng-model="competence.selected"> 

现在,当您选中该复选框,将设置competence.selectedtrue,当你取消它的价值将是false

表单提交

裹在<form>你的表有ng-submit属性,并创建一个函数来提交表单:

<form ng-controller="MyCtrl as vm" ng-submit="vm.submitForm()"> 

    <!-- your table here ... --> 

<input type="submit" value="Submit"> 
</form> 

在你的控制器:

vm.submitForm = function(){ 

    vm.competences.forEach(function(competence){ 

     if(competence.selected) console.log(competence); 

     // or POST the competences using the $http service ... 

    }) 

    } 

见的jsfiddle也:Checkbox Demo

+0

听起来确实不错。没有意识到我可以将“selected”属性添加到视图中的javascript对象。认为我需要在控制器中添加,然后是视图可以访问。非常感谢! –

+0

很酷。不用谢。很高兴我能帮上忙。 –