角度:在对象中使用$scope方法会导致类型错误:未定义不是一个函数



我收到错误:为此TypeError: undefined is not a function

控制器:

$scope.dateRange = { before: $scope.oneMonthAgo(), after: new Date }; #<------
$scope.oneMonthAgo = function oneMonthAgo() {
  var date = new Date;
  date.setMonth(date.getMonth() - 1);
  return date;
};

这是怎么回事??是因为对象无权访问$scope方法吗?

当我将其更改为此值时,它会打印出oneMonthAgo()的正确值:

    $scope.dateRange            = { before: new Date, after: new Date };

    $scope.oneMonthAgo = function oneMonthAgo() {
      var date = new Date;
      date.setMonth(date.getMonth() - 1);
      return date;
    };
    console.log($scope.oneMonthAgo()); # prints Mon Nov 17 2014 11:56:15 GMT-0500 

怎么回事?

您不需要重复函数名称;您还需要在尝试在 dateRange 中使用它之前定义函数。

$scope.oneMonthAgo = function() {
  // ... function stuff here
};
$scope.dateRange = { /* Can make calls to $scope.oneMonthAgo() here */ }

1.在使用之前
需要定义一个月前2 个新日期()而不是新日期

var app = angular.module('app', []);
app.controller('homeCtrl', function($scope) {
  $scope.oneMonthAgo = function oneMonthAgo() {
    var date = new Date();
    date.setMonth(date.getMonth() - 1);
    return date;
  };
  $scope.dateRange = {
    before: $scope.oneMonthAgo(),
    after: new Date()
  };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
  <div ng-controller="homeCtrl">
    DateRange:
    <br/>{{dateRange | json}}
  </div>
</div>

最新更新