我在使用工厂和服务时遇到了一个奇怪的错误。这是我的控制器脚本
/*
*
*
* AdvanceSettingsController
*
*
*/
angular.module('advanceSettings', [])
.config([function () {
}])
.run(['$rootScope', 'CampaignsService', function ($rootScope, CampaignsService) {
CampaignsService.init();
}])
//Common Ajax factory to make ajax requests and assign results in controller's scope
.factory('AjaxRequests', ['$http', function ($http) {
return {
getCampaignsData: function () {
return $http.get(SITEURL + 'tests/all_camp')
}
}
}])
.service('CampaignsService', ['$rootScope', 'AjaxRequests', function ($rootScope, AjaxRequests) {
this.init = function () {
this.$rowsData = {
items: []
};
AjaxRequests.getCampaignsData().success(function (response) {
this.$rowsData.items.push(response.campaigns);
})
};
this.getRows = function () {
return this.$rowsData;
}
}])
.controller('AdvanceSettingsController', ['$scope', 'CampaignsService', 'AjaxRequests', '$http', function ($scope, CampaignsService, AjaxRequests, $http) {
$scope.CampaignsService = CampaignsService;
}
])
.value('version', '0.0.1-br.1');
;
'use strict';
在我的视图模板中,我正在调用服务的功能。像
<div class="row" ng-repeat="row in CampaignsService.getRows() track by $index">
//My code
</div>
第一次调用CampaignService的init函数并初始化this。$ rowsData对象。我的问题是,成功ajax调用后显示未定义的错误,为什么?我收到错误TypeError: this.$rowsData is undefined
如果我在ajax成功调用之后初始化rowsData对象,我的代码可以工作,但为什么我需要在那里进行初始化。这通常被称为不良做法。请建议我正确的方法。提前谢谢。