使用ng-repeat时如何获取复选框的值?

时间:2014-07-03 07:35:35

标签: javascript angularjs checkbox ng-repeat

view.html中的

代码:

<label ng-repeat = "agents in acesslevel |filter:{acesslevel: 'Agent'}">
    <div class="col-xs-2">
        <input type= "checkbox"
               ng-model="agentsSelected"
               checklist-value="agents.name"
               ng-true-value=agents ng-false-value="'NO'">
        {{agents.name}}
    </div>
</label>

其中acesslevel是我从我的数据库获取的json格式数据。

e.g。

{
  "acesslevel": "Quality",
  "dob": "1995-02-03",
  "name": "anjali",
  "password": "tanya",
  "username": "anju",
  "createdAt": "2014-07-02T16:26:26.816Z",
  "updatedAt": "2014-07-02T16:26:26.816Z",
  "id": "53b432b230aaa394278522ca"
},

{
  "acesslevel": "Agent",
  "dob": "1995-02-03",
  "name": "christopher",
  "password": "tanya",
  "username": "anju",
  "createdAt": "2014-07-02T16:26:48.170Z",
  "updatedAt": "2014-07-02T16:26:48.170Z",
  "id": "53b432c830aaa394278522cb"
}

html中的这个特殊代码是在acesslevel中显示代理的名称(在上面的例子中它将显示christopher)

现在我想要的是如何获得控制器中所选复选框的值

我想在数据库服务器的新表中插入此选定的代理数据。

1 个答案:

答案 0 :(得分:0)

问题是你使用的ng-model绑定到(我想的是)一个数组,但angular需要一个布尔值(true或false)。

如果您改为绑定到已过滤的访问级别数组的实例的属性,则可以稍后在控制器中提取该数据

<label ng-repeat = "agents in acesslevel |filter:{acesslevel: 'Agent'}">
    <div class="col-xs-2">
        <input type= "checkbox"
               ng-model="agents.isSelected" <!-- bind to another value -->
               checklist-value="agents.name"
               ng-true-value="agents"
               ng-false-value="'NO'">
        {{agents.name}}
    </div>
</label>

如果您有一个向后端提交值的方法,您的控制器可以稍后访问此属性。

$scope.submit = function() {
    var selectedAgents = [];
    angular.forEach($scope.acesslevel, function (agent) {
        if (agent.acesslevel == 'Agent' && agent.isSelected) {
            selectedAgents.push(agent);
        }
    });
    // here you can make calls to your backend with the selectedAgents variable.

};