将复选框值传递给JS

时间:2017-05-01 11:41:00

标签: javascript html angularjs

我是Angular的新手,通过实施聊天应用程序来学习。  我试图将复选框值传递给我的JS代码。以下是片段。我面临的问题是我无法在JS中获取已检查的值。我的i.value是未定义的。你能指出我哪里出错吗?

<div class="add-friends panel-primary panel" ng-show="addfriendsselected">
  <div class="panel-heading text-center" >Add Friends</div>
    <div class="panel_body">
      <div class="row" id=myForm>
        <ul class="list-group">

          <li class="list-group-item" ng-repeat = "user in friendslist">
            <div>
            {{user.firstName}}
            {{user.email}}
            &nbsp;&nbsp;
            <input type="checkbox" name="checkbox" value= "{{user}}">
            </div>
          </li>
          <div ui-view></div>
        </ul>
      </div>
    </div>
  <form id=userForm ng-submit="createGroup()"> 
    <input class="btn btn-default"  type="submit" value="Create Group"> 
    </form>
</div>

控制器

$scope.createGroup = function() {
   console.log("Entered createGroup ");

   $("input[type=checkbox]:checked").each(function(i){
     console.log("i.value :"+i.value);
     $scope.people.push( i.value );
   });
 console.log("$scope.people : " + JSON.stringify($scope.people));
            }

2 个答案:

答案 0 :(得分:0)

只需将对象属性ng-model添加到复选框

即可

<input type="checkbox" name="checkbox" ng-model="user.check">

angular.module("app",[])
.controller("ctrl",function($scope){

$scope.friendslist = [{"firstName":"sss","email":"ss#gmail.com"}]
$scope.createGroup = function() {

  console.log($scope.friendslist)
}



})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
 <div class="add-friends panel-primary panel" >
  <div class="panel-heading text-center" >Add Friends</div>
    <div class="panel_body">
      <div class="row" id=myForm>
        <ul class="list-group">

          <li class="list-group-item" ng-repeat = "user in friendslist">
            <div>
            {{user.firstName}}
            {{user.email}}
            &nbsp;&nbsp;
            <input type="checkbox" name="checkbox" ng-model="user.check">
            </div>
          </li>
          <div ui-view></div>
        </ul>
      </div>
    </div>
  <form id=userForm ng-submit="createGroup()"> 
    <input class="btn btn-default"  type="submit" value="Create Group"> 
    </form>
</div>
</div>

答案 1 :(得分:0)

建议您使用ngModel的Angular文档中显示的li指令。

此外,为friendslist中的每个/iqn\.[0-9]{4}-[0-9]{2}(?:\.[A-Za-z](?:[A-Za-z0-9\-]*[A-Za-z0-9])?)+(?::.([^,:\s']+))?|eui\.[0-9A-Fa-f]{16}/ 创建单独的组件(或指令)可能很有用。

希望它有所帮助。祝你好运;)