2016-12-05 86 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

很酷。不用謝。很高興我能幫上忙。 –