AngularJS服务TypeError

时间:2015-02-04 08:06:55

标签: javascript angularjs angularjs-scope

我想在AngularJS服务中捕获我的查询的url

var mortgageloanService = angular.module('loanstreetIpadAppApp', []);

mortgageloanService.factory('updateTable', function($http) {

return {
        getParams: function() {

        var url = 'https://api.mongolab.com/api/1/databases/angularjs-intro/collections/users?apiKey=terrPcifZzn01_ImGsFOIZ96SwvSXgN9';

                console.log('in service mode');
                console.log(url);
                return $http.get(url);      
    }
};
});

这是我的controller.js代码

angular.module('loanstreetIpadAppApp')
    .controller('Mortgage_LoanCtrl', function ($location, $scope) {
    $scope.update_result = function(updateTable) {

        updateTable.getParams().success(function(loan){$scope.loan = loan});
        console.log($scope.resulttable);

    };
});

在我的视图页面上,我有一个onclick shud调用update_result函数的按钮。但每当我点击按钮时,我都会收到以下错误

 TypeError: Cannot read property 'getParams' of undefined
    at Scope.$scope.update_result (http://localhost:9003/scripts/controllers/mortgage_loan.js:22:16)
    at http://localhost:9003/bower_components/angular/angular.js:10567:21
    at http://localhost:9003/bower_components/angular/angular.js:18627:17
    at Scope.$eval (http://localhost:9003/bower_components/angular/angular.js:12412:28)
    at Scope.$apply (http://localhost:9003/bower_components/angular/angular.js:12510:23)
    at HTMLButtonElement.<anonymous> (http://localhost:9003/bower_components/angular/angular.js:18626:21)
    at HTMLButtonElement.jQuery.event.dispatch (http://localhost:9003/bower_components/jquery/dist/jquery.js:4430:9)
    at HTMLButtonElement.elemData.handle (http://localhost:9003/bower_components/jquery/dist/jquery.js:4116:28)

任何人都知道如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

要在控制器内使用updateTable工厂,您需要注入它。所以,你的控制器应该是这样的。

angular.module('loanstreetIpadAppApp')
    .controller('Mortgage_LoanCtrl', function ($location, $scope, updateTable) {
    $scope.update_result = function() {

        updateTable.getParams().success(function(loan){$scope.loan = loan});
        console.log($scope.resulttable);

    };
});

请注意,我已删除&#34; updateTable&#34; as&#34; $ scope.update_result&#34;&#39;的参数,因为它会覆盖该闭包内的updateTable对象。