這是一種可能的方法。請參閱行內註釋以解釋。
app.controller('MainCtrl', function($scope, $filter) {
// set up your model
$scope.allPermissions = [
{ "id" : 3, "name" : "ADMIN", selected: false },
{ "id" : 2, "name" : "READ", selected: false },
{ "id" : 1, "name" : "WRITE", selected: false } ];
// Use $watch to detect changes in the model.
// But you might as well want to call this from an event or whatever...
$scope.$watch('allPermissions', function(newval, oldval){
if (oldval != newval)
{
// only return the checked values using $filter
var selectedPermission = $filter('filter')($scope.allPermissions, {selected: true});
// 'selectedPermission' will return a list of all selected permissions.
// Use 'selectedPermission[0].id' to return the first value.
$scope.admin_events = selectedPermission[0].id;
}
},true);
});
而在你的HTML
<body ng-controller="MainCtrl">
<p ng-repeat="permission in allPermissions">
<input type="checkbox" ng-model="permission.selected"/>
{{permission.name}}
</p>
admin_events: {{admin_events}}
</body>
我個人會使用ng-options進行下拉菜單,您可以根據值 – stackg91
顯示文本,但是我有一個關於ng-options的問題,我不能使用它,因爲我的admin_event只是一個包含整數值的變量,它不是一個3整數的數組。所以我不能在admin_event中重複這些選項。 – leo277