使用ng-model和ng-repeat进行多次默认选择

时间:2017-04-04 10:52:53

标签: javascript html angularjs select

<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>

我想通过defalut用ng-model绑定选择值我想只使用ng-repeat而不是ng-options默认情况下sholud选择$ scope.user.roles值中的值

2 个答案:

答案 0 :(得分:1)

这个怎么样??

&#13;
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

也许这会对你有所帮助:

<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>
相关问题