【问题标题】:multiple default select with ng-model and ng-repeat使用 ng-model 和 ng-repeat 进行多个默认选择
【发布时间】:2017-08-29 12:45:39
【问题描述】:
<script src="" https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js ""></script>
<script>
  var app = angular.module('role', []);

  app.controller('fooController', function($scope) {
    $scope.roles = [{
      id: 1,
      name: "Administrator"
    }, {
      id: 2,
      name: "Student"
    }, {
      id: 3,
      name: 'worker'
    }];
    $scope.user = {};
  $scope.value=function(){
    $scope.user = [name:'abc',roles:[{
      id: 2,
      name: 'Student'
    }, {
      id: 3,
      name: 'worker'
    }];
      }
  });
</script>

<body>
   <button type="button" ng-click="value()">Click me </button>
    <form ng-repeat="test in user">
   <input type="text" ng-model="test.name">
  <select multiple class="form-control" data-ng-model="user.roles" required>
    <option ng-repeat="role in roles" value="{{role.id}}">{{role.name}}</option>
      </select>
</body>

我想通过默认值与 ng-model 绑定选择值

【问题讨论】:

  • 您面临的问题是什么?
  • $scope.user.roles 中的值被选中
  • 因此您希望默认选择 $scope.user.roles 中的值
  • 我想要多个 select@charlesliam

标签: javascript html angularjs select


【解决方案1】:

这个怎么样?

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script>
  var app = angular.module('role1', []);

  app.controller('fooController', function($scope) {
    $scope.roles = [{
      id: 1,
      name: "Administrator"
    }, {
      id: 2,
      name: "Student"
    }, {
      id: 3,
      name: 'worker'
    }];
    $scope.user = {};

    $scope.user.roles = [{
      id: 2,
      name: 'Student'
    }, {
      id: 3,
      name: 'worker'
    }];
    $scope.user.roles.id = $scope.user.roles.map(function(a) {
      return a.id;
    });
  });
</script>

<body ng-app="role1" ng-controller="fooController">
  <select multiple class="form-control" data-ng-value="user.roles" required>
<option ng-repeat="role in roles" ng-selected="user.roles.id.indexOf(role.id) != -1" value="{{role.id}}">{{role.name}}</option>
  </select>
</body>

【讨论】:

【解决方案2】:

也许这会对你有所帮助:

<select multiple class="form-control" data-ng-model="user.roles"  required>
<option ng-repeat="role in roles" value="{{role.id}}" ng-selected="{{user.roles.indexOf(role) !== -1}}">{{role.name}}</option>
</select>

【讨论】:

    猜你喜欢
    • 2023-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多