2013-12-18 74 views
0

我試圖從綁定到複選框的$ rootScope對象獲取值。如何從複選框獲取價值?在Angular JS

HTML:

<tr ng-repeat="system_history in SystemHistoryResponse.system_history"> 
<td><input type="checkbox" ng-model="versionValues[system_history.version]"></td> 
</tr> 

JS:

$rootScope.versionValues = {}; 

輸出現在:

versionValues: {"321":true,"322":true} 

希望的輸出:

versionValues: [321, 322] 

回答

1

我只是將對象轉換成一個數組,當我需要它:

var a = {"321":true,"322":true}; 
var b = []; 
var i = 0; 
for(x in a){ 
    b[i++] = parseInt(x,10); 
} 
// b === [321,322] 

否則,您可以使用ngChange指令(注:我沒有測試此代碼):

html: 
<input type="checkbox" ng-model="versionValues[system_history.version] 
ng-change="update(system_history.version)" 
"> 
js: 
$rootScope.versionValues = {}; 
$rootScope.versionValuesArray = []; 
$rootScope.update(version){ 
    if($rootScope.versionValues[version]){ 
     // add version to $rootScope.versionValuesArray 
    }else{ 
     // remove version from $rootScope.versionValuesArray 
    } 
} 

但與此相關的問題是,需要線性時間插入和從數組中移除,這與將整個對象轉換爲數組的時間大小相同。

+0

第二種方法工作得很好!謝謝你哦! –