如何根据angularjs中的其他变量更改ng选项值?

xdnvmnnf  于 2021-09-29  发布在  Java
关注(0)|答案(1)|浏览(274)

我想更改下拉菜单取决于复选框。因此,如果选中复选框,则仅显示特定项目。

<script>
angular.module('selectExample', [])
  .controller('ExampleController', ['$scope', function($scope) {

    $scope.colors=[
      {id:1, name:'black'},
      {id:2, name:'red'}, 
      {id:3, name:'white'},
    ]
    $scope.myColor = $scope.colors[2]; // red
    $scope.isFlagOn = false;

    function showFlag(){
      if ($scope.isFlagOn){
        return [$scope.colors.find(s => s.name === $scope.myColor)];
      }
      else{
        return $scope.colors
      }
    }

  }]);
</script>
<div ng-controller="ExampleController">

  <label>
     isFlagOn <input type="checkbox" ng-model="$scope.isFlagOn">

  </label>
  <br/><br/>
  <select ng-model="myColor" ng-options="color as color.name for color in $scope.showFlag() track by color.id">
    <option value="">Choose one</option>
    </select><br/><br/>

</div>

若复选框被选中,我只想在这里显示红色选项。是否可以使用“ng选项”?
谢谢

iyr7buue

iyr7buue1#

还有一种方法。您可以使用以下选项筛选ng选项:

ng-options="color.id as color.name for color in colors | filter:{name: isFlagOn? myColor.name : ''} "

也, $scope 绑定到html-其中的每个变量都会自动 $scope 因此,在html中不使用它,只在js(例如控制器)中使用它。

angular.module('selectExample', [])
  .controller('ExampleController', ['$scope', function($scope) {
    $scope.colors = [{id: 1, name: 'black'},
      {id: 2, name: 'red'},
      {id: 3,name: 'white'},
    ]
    $scope.myColor = $scope.colors[2]; // red
  }]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.10/angular.min.js"></script>
<div ng-app="selectExample">
<div ng-controller="ExampleController">
  <label> isFlagOn <input type="checkbox" ng-model="isFlagOn">
  </label>
  <br/><br/>
  <select ng-model="myColor" ng-options="color.id as color.name for color in colors | filter:{name: isFlagOn? myColor.name : ''} ">
    <option value="">Choose one</option>
  </select><br/><br/>
</div>
</div>

相关问题