angularjs - 检查 ng-repeat 和 $http 中的值将其发布 AngularJs

标签 angularjs http post

<分区>

我正在尝试在 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>

我想要选中一些 复选框 的选项,然后单击 post 并且 $http 调用正在运行。 我的笨蛋:http://next.plnkr.co/edit/zPu9DH0JyinlBvLh 提前感谢您的回答和帮助!

最佳答案

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

$scope.modelCheck = {};

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

<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
    };

查看此 Forked working plunker (查看控制台)

关于angularjs - 检查 ng-repeat 和 $http 中的值将其发布 AngularJs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51712487/

相关文章:

javascript - 成功后使用 dropzone 更新 Angular js 上的选项卡

java - 使用矩阵参数创建 GET 请求

android - 如何在 POST 请求后调试空响应

javascript - 使用 jquery ajax 与 native xhr

javascript - angular js - 获取json数据

javascript - AngularJS 在属性数组中组合对象

javascript - 将jquery插件应用于angularJS ng-repeat中的新项目

javascript - Angular 8 - HttpClient 获取复杂的 JSON 对象

ruby - Sinatra HTTP 'PUT' 方法

http - 是否可以使用内容编码 : gzip in a HTTP POST request?