Angularjs select multiple options from object

前端 未结 4 1692
野趣味
野趣味 2020-12-11 02:34

Trying to select multiple options in angularjs regarding to object values

Here is a code:

myapp.controller(\'myctrl\', [
        \'$scope\',
                 


        
4条回答
  •  臣服心动
    2020-12-11 02:45

    You're trying to use a select multiple like a checkbox list, which is a little strange. Multi-selects output an array. You can't put ng-model on an option tag like that, it goes on the select itself. So since the select will output an array of values, you'll need to loop through the values and update the nodes in your scope.

    Here's a plunk demonstrating the code

    And here's the code:

    JS

    function inArray(x, arr) {
      for(var i = 0; i < arr.length; i++) {
        if(x === arr[i]) return true;
      }
      return false;
    }
    
    app.controller('MainCtrl', function($scope) {
       $scope.query = {
                    Statuses: {
                        Draft: true,
                        Live: true,
                        Pending: true,
                        Archived: false,
                        Deleted: false
                    }
                };
      $scope.selectionsChanged = function(){
        for(var key in $scope.query.Statuses) {
          $scope.query.Statuses[key] = inArray(key, $scope.selectedValues);
        }
      };
    });
    

    HTML

    
    
    {{query | json}}

    I hope that helps.

提交回复
热议问题