2013-05-11 62 views
0

我需要將選中的複選框打包在一起才能POST到我的服務器。在每個複選框的屬性中,我存儲了兩個重要的值:「pos」(詞性)和定義。我需要運行這些複選框中的每一個,將其推送到JSON數組,並在按下「添加字」按鈕時將其發送出去。使用角度獲取所有選中的複選框及其相關屬性

<input type="checkbox" name="definition-checkbox" pos="noun" definition="Hill, rolling grassland" class="ng-valid ng-dirty"> 

我想打開復選框爲元素的限制指令並以某種方式做的事情有,但我不知道如何去及彼的所有值,而不做每件都有些循環似乎是非角度的。

有什麼建議嗎?

Prototype

回答

4

這很難說,其中來自posdefinition屬性字符串從何而來,但棱角分明,你希望你的意見是一些數據的反映這是在範圍訪問 - 改變你的查看(例如,選中一個框)應該更改您範圍內的一些數據。

在這種特殊情況下,我期望在對象上看到posdefinition;也許控制器可以訪問它們的數組。

app.controller('WordController', function($scope) { 
    $scope.word = 'property'; 

    // Maybe this array came from an $http call; maybe it was injected 
    // into the page with `ngInit` or `$routeProvider`. 
    // The point is, the controller has a client-side representation of 
    // the data you want to show *and manipulate* in the view. 
    $scope.definitions = [ 
    { checked: false, pos: 'noun', definition: 'Something that is owned' }, 
    { checked: false, pos: 'noun', definition: 'A piece of real estate, such as a parcel of land' }, 
    { checked: false, pos: 'noun', definition: 'real estate; the business of selling houses' }, 
    { checked: false, pos: 'noun', definition: 'The exclusive right of possessing, enjoying and disposing of a thing' } 
    // ... 
    ]; 
}); 

現在這個信息的範圍,您可以輕鬆地給它綁定在你的觀點:

<div ng-repeat='definition in definitions'> 
    <input type='checkbox' ng-model='definition.checked'> {{definition.definition}} 
</div> 
<input type='submit' ng-click='submitDefinitions()' value='Add Word'> 

由於當點擊複選框直接修改每個定義的.checked屬性時,submitDefinitions方法在控制器上可以容易地確定選擇哪個定義:

app.controller('WordController', function($scope) { 
    // ... 

    $scope.submitDefinitions = function() { 
    var selectedDefinitions = $scope.definitions.filter(function(def) { 
     return def.checked; 
    }); 
    // do something with selected definitions 
    }; 
}); 

下面是一個說明基本技術中的的jsfiddle :http://jsfiddle.net/BinaryMuse/cTBm4/

+0

謝謝。簡單用例的絕佳解決方案。 – rekordboy 2015-05-07 21:21:40

相關問題