Angular:在对象中使用$ scope方法会导致TypeError:undefined不是函数

时间:2014-12-17 17:00:35

标签: angularjs

我收到了错误: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 

这笔交易是什么?

2 个答案:

答案 0 :(得分:6)

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

$scope.oneMonthAgo = function() {
  // ... function stuff here
};

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

答案 1 :(得分:1)

1.在使用之前,您需要定义oneMonthAgo 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>