我如何通过angularjs操纵选择选项

时间:2016-10-02 20:06:32

标签: angularjs angularjs-ng-options

我有以下问题,我有3个选择字段(由ngOptions生成),几个选项(100,200,300)。例如,宽度为顶部底部的选项(此宽度在此字段中相同)并且我有2个条件:< / p>

  1. 宽度顶部不能大于侧边宽度(所以如果宽度 边是100,顶部宽度可以等于0到100)。
  2. 宽度 底部可以大于侧面(所以如果宽度边是100,那么 底部宽度可以超过100)
  3. 并且在选择之后我需要从选择字段访问这个指定的值。

    我必须通过指令在angularjs中执行此操作。

    &#13;
    &#13;
    angular.module('myApp', [])
    .controller('Ctrl', function($scope) {
        $scope.widths = [{ width: 300 }, { width: 500 }, { width: 400 }];
    });
    &#13;
    <html ng-app="myApp">
    <head>
    	<title></title>
    </head>
    <body>
    <div ng-controller="Ctrl">
      
            <select ng-model="player" ng-options="w.width for w in widths track by w.width" id="top"></select>
            <select ng-model="player2" ng-options="w.width for w in widths track by w.width" id="sides"></select>
            <select ng-model="player3" ng-options="w.width for w in widths track by w.width" id="bottom"></select>
        </div>
      <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
      </body>
      </html>
    &#13;
    &#13;
    &#13;

1 个答案:

答案 0 :(得分:0)

您可以使用函数返回ng-select中的选项 。您已经定义了$ scope.player,$ scope.player1,$ scope.player2等变量。确保将三个变量初始化为默认值(否则未定义,并在下拉列表中显示为空白选项)

&#13;
&#13;
angular.module('myApp', [])
.controller('Ctrl', function($scope) {
    $scope.widths = [{ width: 300 }, { width: 500 }, { width: 400 }];
    $scope.getTopOptions = function () {
                var ret = [];
                if (!$scope.player2) {
                    return $scope.widths;
                }
                angular.forEach($scope.widths, function (width) {
                    if (width.width <= $scope.player2.width) {
                        ret.push(width);
                    }
                });
                return ret;
            };

            $scope.getBottomOptions = function(){
                var ret = [];
                if(!$scope.player2){
                    return $scope.widths;
                }
                angular.forEach($scope.widths, function (width) {
                    if (width.width > $scope.player2.width) {
                        ret.push(width);
                    }
                });
                return ret;

            }
});
&#13;
<html ng-app="myApp">
<head>
	<title></title>
</head>
<body>
<div ng-controller="Ctrl">
  
        <select ng-model="player" ng-options="w.width for w in getTopOptions() track by w.width" id="top"></select>
        <select ng-model="player2" ng-options="w.width for w in widths track by w.width" id="sides"></select>
        <select ng-model="player3" ng-options="w.width for w in getBottomOptions() track by w.width" id="bottom"></select>
    </div>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
  </body>
  </html>
&#13;
&#13;
&#13;