Angularjs 如何让复选框被选中?

新手上路,请多包涵

您好,我正在使用 angularjs 开发 Web 应用程序。我有一种形式。我将值绑定到多选下拉列表。

   <li ng-repeat="p in locations">
  <input type="checkbox" ng-checked="master" ng-model="isTrue" ng-change="getIndex(p.Location,isTrue )" ng-name="location" required/>
  <span>{{p.Location}}</span>
  </li>

我将数组绑定到位置。我的数组看起来像

0:  id: 1  Location:"ABC"
1:  id: 2  Location:"DEF"
2:  id: 3  Location:"IJK"

现在我的要求是检查一些值。假设如果我有 var locations="ABC,DEF" 那么我只想检查那些值。我可以知道这是否可以完成。任何帮助,将不胜感激。谢谢你。

原文由 Niranjan Godbole 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 250
2 个回答

基本上,如果我们的输入是一个包含应该选择的位置的字符串(即) var locations = 'ABC,DEF'; 我们可以将这个字符串拆分为 , 字符并获得一个包含要匹配的位置的数组:

 var app = angular.module('myApp', []);

app.controller("locationsController", ["$scope",
    function ($scope) {
        // vars
        var locations = 'ABC,DEF';

        // functions
        function init () {
            var locals = locations.split(',');

            angular.forEach($scope.locations, function (item) {
                if (locations.indexOf(item.Location) > -1) {
                    item.checked = true;
                }
            });
        }

        // $scope
        $scope.locations = [
            { id: 1, Location: "ABC" },
            { id: 1, Location: "DEF" },
            { id: 1, Location: "IJK" }
        ];

        // init
        init();
    }
]);
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
   <div ng-controller="locationsController">
      <li ng-repeat="p in locations">
         <input ng-checked="p.checked" type="checkbox" ng-model="p.checked" required/>
         <span>{{ p.Location }}</span>
      </li>
   </div>
</div>

原文由 Daniel 发布,翻译遵循 CC BY-SA 3.0 许可协议

它应该工作:-

 var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope,$filter) {

  $scope.selectedValue = 'ABC,IJK';
  $scope.selectedValue = $scope.selectedValue.split(',');

  $scope.options = [{
    id: 0,
    name: 'ABC'
  }, {
    id: 1,
    name: 'DEF'
  }, {
    id: 2,
    name: 'IJK'
  }];
  $scope.selected = [];
  angular.forEach($scope.selectedValue,function(val,key){
  var r = $filter('filter')( $scope.options, {name: val})[0].id;
  if(r != undefined){
   $scope.selected[r]=true;
  }else{
   $scope.selected[r]=false;
   }


  });


});
 <!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>

<body>

  <div ng-app="myApp" ng-controller="myCtrl">

    <li ng-repeat="p in options">
      <input type="checkbox" ng-model="selected[p.id]" ng-change="getIndex(p.Location,isTrue )" />
      <span>{{p.name}}</span>
    </li>
    Selected : {{selected}}
  </div>

原文由 Gaurav Srivastava 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题