【问题标题】:how to get the object from ng-repeat checkbox values in Angular JS如何从Angular JS中的ng-repeat复选框值中获取对象
【发布时间】:2016-01-03 18:40:09
【问题描述】:

我遇到了问题,希望有人能提供帮助。

现在,我在表单中显示了几个从我的 firebase 数据库中获取的复选框。在我的控制器中,我试图使用 ng-submit 来存储表单的整个数据。 我的复选框 JSON 格式应如下所示。

{
    "apple" : true,
    "spotify" : true 
}

The checkbox image here

好的,下面是我的 HTML 和 Javascript 代码

<label class="checkbox-inline" ng-repeat="hashtag in hashtags" for="{{hashtag}}">
  <input type="checkbox" name="{{hashtag.$value}}" id="{{hashtag.$value}}" value="{{hashtag.$value}}" ng-model="hashtag.SELECTED" ng-true-value="true" ng-false-value="false"> 
    {{hashtag.$value | capitalize}}
</label>

我的 Javascript 在这里

form.$add({
    description: $scope.inputDescription,
    hashtags: {
        *I don't know how to put checkbox's result here.*
    },
    time: Firebase.ServerValue.TIMESTAMP,
    title: $scope.inputTitle,
    url: $scope.inputUrl
})

有人可以帮忙吗?非常感谢。

更新 谢谢回复。我真的很感激那些!但是,我发现我忘了提一些东西,我尝试了回复中的答案,但没有奏效。下面的图片将解释我的问题。 enter image description here 非常感谢!

最终解决方案以防人们对我刚刚找到的答案感到好奇。以下是我的解决方案。谢谢你们!我喜欢stackoverflow!

function checkbox(hashtags) {
    var arr = {};
    for(var hashtag in hashtags) {
        if(hashtags[hashtag].SELECTED === true){
            arr[hashtags[hashtag].$value] = true;
        }
    }
    return arr;
}

【问题讨论】:

  • hashtags第一个描述的JSON吗?

标签: javascript angularjs checkbox angularjs-scope angularjs-ng-repeat


【解决方案1】:

类似这样,我在一个类似的问题中找到了信息:

<input type="submit" name="submit" value="submit" ng-click="check(hashtags)"/>

$scope.check= function(data) { 
var arr = [];
for(var i in data){
   if(data[i].SELECTED=='Y'){
       arr.push(data[i].value);
   }
}
//At this points you have all the selected hashtags on arr Array

}

【讨论】:

  • 非常感谢克里斯!我做到了。起初我用你的答案,但不知何故只是没有用。我再次使用了这个答案并稍微抽搐了一下,这次它起作用了!谢谢你!
【解决方案2】:

尝试将您的 ng-model 更改为

ng-model="mhashtags[hashtag.$value]"

有了这个,你的作用域中就会有一个 mhashtags 变量,这正是你需要发送的。

【讨论】:

    【解决方案3】:

    假设 hashtags 是这个 JSON:

    $scope.hashtags = {
      "apple" : true,
      "spotify" : true 
    };
    

    我会将 ng-repeat 更改为:

    <label class="checkbox-inline" ng-repeat="(hashtag, bool) in hashtags" for="{{hashtag}}">
      <input type="checkbox" name="{{hashtag}}" id="{{hashtag}}" ng-value="bool" ng-model="hashtag"> 
        {{hashtag | capitalize}}
    </label>
    

    hashtag是对象的key,bool是value,所以不需要"$value"。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-24
      • 2014-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多