比方說,你定義你的模型,例如:
function Ctrl($scope) {
$scope.items = [{
name: 'A',
checked: false
}, {
name: 'B',
checked: false
}, {
name: 'C',
checked: false
}, {
name: 'D',
checked: false
}];
}
,創造了模型中的觀點:
<ul>
<li ng-repeat="item in items">
<label>
<input type="checkbox" ng-model="item.checked">
{{item.name}}
</label>
</li>
</ul>
<button ng-click="save()">save</button>
接下來,您必須定義save
功能:
$scope.save = function() {
//angular.toJson converts array to string, something like
// '[{"name":"A","checked":false},{"name":"B","checked":true},...]'
var json = angular.toJson($scope.items);
//Service is angular service for your model that makes http requests to your backend
Service.save(json).then(function(){
//here you can notify user that data is persisted
}, function() {
//here you can notify user that there was a problem with request
});
}
和一個簡單的模型服務:
.service('Service', function($http) {
return new function() {
this.save = function(data) {
return $http.post('url/to/backend', data);
}
}
});
感謝您的快速回復格言。我想將複選框值保存爲模型字段中的json字符串。 因此,當用戶點擊保存,產生這個字符串: [ {名稱:「蘋果」,檢查:真正}, {名稱:「橙」,檢查:假} ] 並保存到像模特team.fruits。 你能提出一些關於如何使用狀態改變來實現這個目標的代碼嗎? 再次感謝。 – kSeudo
再次感謝您的超級快速回復Maxim。我如何傳遞{{fruits |}評估的值json}}發送到控制器,以便將其保存到模型字段中,例如「foods.fruits」?目前我只是不知道如何將這個值傳遞給控制器... – kSeudo
控制器有'$ scope.fruits' - 這是你的模型,如果你使用GUI支付(用基本單詞),這個模型會改變 –