检查ng repeat和$http post-it AngularJs中的值



我正在尝试在ng-repeat中添加复选框,然后使用$http的复选值发布。这是我的代码:

$scope.add_to_post = function(n){
console.log("name",n);
$http({
method: 'POST',
url: url,
data: $.param({
name: n,
}),
withCredentials: true,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
})
.then(function successCallback(data) {
console.log('post');
}, function errorCallback(response) {
console.log(response);
console.log('error');
});
};

HTML:

<div >
<ul ng-repeat="x in messages" style="list-style:none;">
<li>
{{x.name}}
<input type="checkbox" ng-click="add_to_post(x.name)"/>
</li>
</ul>
<button ng-click="post()">post</button>

我想要的选项是,我检查一些checkboxes,然后单击post$http调用正在运行。我的傻瓜:http://next.plnkr.co/edit/zPu9DH0JyinlBvLh感谢您的回答和提前提供的帮助!

在控制器中,您可以创建一个对象来存储复选框的模型(ng-model(,如下所示:

$scope.modelCheck = {};

然后在html中,你可以像这样绑定它们:

<input type="checkbox" ng-model="modelCheck[x.name]"/>

最后,当您要进行POST收集复选框名称时,该名称标记为true,如下所示:

$scope.post = function(){
var data = [];
for (var k in $scope.modelCheck) {
// `k` is own property (checkbox name) and its value is `true`
if ($scope.modelCheck.hasOwnProperty(k) && $scope.modelCheck[k]) {
data.push({'name': k});
}
}
console.log(data);
// do with data as you wish from here
};

请参阅此叉式工作锤(请参阅控制台(

最新更新