在下拉列表中设置默认值

时间:2017-08-21 08:56:58

标签: javascript angularjs drop-down-menu

我有一个下拉列表。我的目标是在下载时将下拉列表设置为“默认”

<b>Filter Within Months:</b>
<select  class="btn green" ng-model="myOptions" ng-options="i.label for i in items track by i.id" ng-change="selectedItemChanged()">
</select>

controller.js 在加载时将模型设置为“默认”。

$scope.myOptions.id = 0;
$scope.items = [{
  id: 0,
  label: 'Default'
}, {
  id: 1,
  label: 'All'
}, {
  id: 2,
  label: '3 month'
}, {
  id: 3,
  label: '6 month'
}, {
  id: 4,
  label: 'Previous Month'
}];

$scope.selectedItemChanged = function() {
  var date = new Date();
  var endDate = Date.now();
  var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
  var firstDayOfPreviousMonth = new Date(date.getFullYear(), date.getMonth() - 1, 1)
  var lastDayOfPreviousMonth = new Date(date.getFullYear(), date.getMonth(), 0)

  if ($scope.myOptions.id === 1) { //show All
    startDate = null;
  } else if ($scope.myOptions.id === 2) { //show 3 month
    startDate = date.setDate(date.getDate() - 90);
  } else if ($scope.myOptions.id === 3) { //show 6 month
    startDate = date.setDate(date.getDate() - 180);
  } else if ($scope.myOptions.id === 4) { //show Previous Month
    startDate = Date.parse(firstDayOfPreviousMonth);
    endDate = Date.parse(lastDayOfPreviousMonth);
  } else { //Default
    startDate = Date.parse(firstDay)
  }
  $scope.selectedDateFilterRange();
}

$scope.selectedDateFilterRange = function() {
  //filter the data
}

但是每当我运行代码时都会出现错误

  

TypeError:无法设置未定义的属性“id”   $ scope.myOptions.id = 0;

2 个答案:

答案 0 :(得分:2)

您正在尝试设置未定义对象的属性myOptions不存在。

更改$scope.myOptions.id = 0;

致:

$scope.myOptions = { "id": 0 };
// Or $scope.myOptions = {};
//    $scope.myOptions.id = 0;

Working demo

答案 1 :(得分:-1)

试试这个

var index = _.findIndex($scope.items,{id:0});
$scope.myOptions = $scope.items[index];

注意:第一行需要使用underscore.js,但您可以使用纯javascript替换它以获取 $ scope.items 中id = 0的项目的索引