TypeError:无法读取未定义的属性“addTopic”。我瞎了吗?

时间:2015-10-13 18:19:50

标签: javascript angularjs

由于我几天来一直在盯着这个问题,我在AngularJS有点新鲜,我想也许有人可以帮助我。所以对我的问题:

当我尝试在我正在创建的论坛上保存新主题时,我收到了一个Typeerror:我的控制器

module.controller('newTopicController', ['$scope', '$http', 'dataService', function ($scope, $http, $window, dataService) {
$scope.newTopic = {};

$scope.save = function () {

    dataService.addTopic($scope.newTopic)
    .then(function () {
        $window.location = "/#";
    },
    function () {
        alert("couldnt save topic");
    });
};
}]);

我的工厂:

module.factory("dataService", function ($http, $q) {

var _topics = [];
var _isInit = false;

var _isReady = function () {
    return _isInit;
};

var _getTopics = function () {

    var deferred = $q.defer();

    $http.get("/api/topics?withReplies=true")
    .then(function (result) {
        angular.copy(result.data, _topics);
        _isInit = true;
        deferred.resolve();
    },
    function () {
        deferred.reject();
    });

    return deferred.promise;
};

var _addTopic = function (newTopic) {
    var deferred = $q.defer();

    $http.post("/api/topics", newTopic)
   .then(function (result) {
       var createdTopic = result.data;
       _topics.splice(0, 0, createdTopic);
       deferred.resolve(createdTopic);
   },
   function () {
       deferred.reject();
   });

    return deferred.promise;
};

return {
    topics: _topics,
    getTopics: _getTopics,
    addTopic: _addTopic,
    isReady: _isReady
};
});

因此,当我尝试向论坛添加主题时,我只是在控制器中获得“TypeError:无法读取属性'addTopic'的未定义”,就在dataService.addTopic($ scope.newTopic)所在的位置。

我还有另一个也使用工厂的控制器,但这不应该是一个问题吗?

感谢您的时间。

1 个答案:

答案 0 :(得分:3)

这似乎不正确:

module.controller('newTopicController', ['$scope', '$http', 'dataService', function ($scope, $http, $window, dataService) {...}

将其更改为:

module.controller('newTopicController', ['$scope', '$http', '$window', 'dataService', function ($scope, $http, $window, dataService) {...}