javascript - Using Angular services to hold commonly required data -
i writing first application in angular , have been enjoying framework has offer far. newbies set off building main controller, copying tutorials. seeing error of ways , refactoring.
my question services holding data commonly required among controllers.
i've taken data out of 'main controller' , placed service have injected both controllers requiring access. though neither controller sees functionality i've defined in new service:
varianceservice not defined
being new approach welcome , help, aswell current problem, comments on best way apply approach highly appreciated.
thanks in advance.
here example of code:
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); }]);
change this
.controller('variancectrl', ['$scope', 'varianceservice', function ($scope, $http, $location, $routeparams) { $scope.variance_type = varianceservice.getvariances(); }])
to
.controller('variancectrl', ['$scope', '$http', '$location', '$routeparams', 'varianceservice', function ($scope, $http, $location, $routeparams, varianceservice) { $scope.variance_type = varianceservice.getvariances(); }])
Comments
Post a Comment