【发布时间】:2014-04-07 05:00:37
【问题描述】:
我目前正在用 Angular 编写我的第一个应用程序,并且一直非常享受迄今为止框架提供的所有功能。像大多数新手一样,我开始将所有内容构建到主控制器中,复制教程。我现在看到了我的方式和重构的错误。
我的问题是关于保存控制器之间通常需要的数据的服务。
我现在已将数据从“主控制器”中取出,并将其放入已注入到需要访问的两个控制器中的服务中。现在虽然两个控制器都看不到我在新服务中定义的功能:
varianceService is not defined
作为这种方法的新手,我欢迎所有和任何帮助,以及对我当前问题的帮助,任何关于应用这种方法的最佳方法的 cmet 也将受到高度赞赏。
提前致谢。
下面是代码示例:
var app = angular.module(
'VarianceAnalysis', ['ngRoute', 'ngAnimate', 'mgcrea.ngStrap', 'mgcrea.ngStrap.tooltip', 'mgcrea.ngStrap.helpers.dateParser', 'SharedServices']
)
.service('varianceService', function () {
var variances = {};
return {
redirect: function (path) {
$location.path(path);
},
getHttpVariances: function (month1, month2) {
var url = "/Home/GetVariances?month_1=";
url += month1;
url += "&month_2="
url += month2;
url += "&forwardBilling=true"
$http.get(url).success(function (data) {
variances = data;
return data;
});
return {};
},
getVariances: function () {
return variances;
}
};
})
.config(['$routeProvider',
function ($routeProvider) {
$routeProvider.
when('/MainPage', {
templateUrl: 'mainpage.html',
controller: 'MainPageCtrl'
}).
when('/Variance/:type', {
templateUrl: 'variance.html',
controller: 'VarianceCtrl'
}).
otherwise({
redirectTo: '/MainPage'
});
}])
.controller('VarianceCtrl', ['$scope', 'varianceService', function ($scope, $http, $location, $routeParams) {
$scope.variance_type = varianceService.getVariances();
}])
.controller('MainPageCtrl', ['$scope', 'varianceService', function ($scope, $http, $location) {
$scope.go = function (month1, month 2) {
$scope.variances = varianceService.getHttpVariances(month1, month2);
}]);
【问题讨论】:
标签: javascript angularjs model-view-controller