Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在下拉列表中设置默认值_Javascript_Angularjs_Drop Down Menu - Fatal编程技术网

Javascript 在下拉列表中设置默认值

Javascript 在下拉列表中设置默认值,javascript,angularjs,drop-down-menu,Javascript,Angularjs,Drop Down Menu,我有一个下拉列表。我的目标是在加载时将下拉列表设置为“默认” 但是每当我运行代码时,就会出现一个错误 TypeError:无法在处设置未定义的属性“id” $scope.myOptions.id=0 您正在尝试设置未定义对象的属性:myOptions不存在 更改$scope.myOptions.id=0 致: 试试这个 var index = _.findIndex($scope.items,{id:0}); $scope.myOptions = $scope.items[index]; 注意

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

但是每当我运行代码时,就会出现一个错误

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


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

更改
$scope.myOptions.id=0

致:

试试这个

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

注意:第一行需要underline.js,但您可以用纯javascript替换它,以从$scope获取id=0的项的索引。如果我们更改为其他选项,如“All”,则初始化值$scope.myOptions={“id”:0};影响它并将其更改回“默认值”@NithinP.H它将按预期工作。试穿一下,非常感谢
$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
}
$scope.myOptions = { "id": 0 };
// Or $scope.myOptions = {};
//    $scope.myOptions.id = 0;
var index = _.findIndex($scope.items,{id:0});
$scope.myOptions = $scope.items[index];