在select下拉列表中给出表达式的Angular不同选项值或字符串

时间:2017-04-19 10:01:05

标签: angularjs angularjs-directive

我正在使用默认的<select/>字符串创建<option/>,但它依赖于特定的表达式

例如,空数据集将产生“暂无数据”默认选项,而当有可用数据时,默认选项应为“选择数据”

Angular只允许在html页面中使用一个静态选项。

1 个答案:

答案 0 :(得分:0)

使选项描述成为条件(通过将描述移动到函数):

&#13;
&#13;
var myapp = angular.module('myapp', []);
myapp.controller('FirstCtrl', function($scope) {
  $scope.people = [{
    first: 'John', last: 'Rambo'
  }, {
    first: 'Rocky', last: 'Balboa'
  }, {
    first: 'John', last: 'Kimble'
  }, {
    first: 'Ben', last: 'Richards'
  }];
  
  $scope.optionText = function() {
      if($scope.people.length > 0) return 'Select a person';
      else return 'No person found';
  }
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myapp" ng-controller="FirstCtrl">
    <select ng-options="p.first + ' ' + p.last for p in people" ng-model="selectedPerson">
      <option value="">{{optionText()}}</option>
    </select>

    <button ng-click="people = []">Clean data</button>
</div>
&#13;
&#13;
&#13;