Loading json data with an AngularJS factory
You forgot to pass the name of the factory in the array. Typically you pass an array whose elements consist of a list of strings followed by the function itself. Be sure to keep the array in sync with the parameters in the function declaration. This way the injector knows what services to inject into the function.
myApp.controller('smController', ['$scope', 'stadtMobilRates', function($scope, stadtMobilRates) {
EDIT
This is how I would do it...When routes are used I like to use resolve
so the data gets loaded once and is stored. So in the $routeProvider
, I would change the the smController part to the following...
when('/sm', { templateUrl: 'partials/sm.html', controller: 'smController', resolve:{ load:function(stadtMobilRates){ return stadtMobilRates.LoadData(); } }).
I've also modified the factory
myApp.factory('stadtMobilRates', function ($q, $http) {var mobilRates = null;function LoadData() { var defer = $q.defer(); $http.get('stadtmobilRates.json').success(function (data) { mobilRates = data; defer.resolve(); }); return defer.promise;}return { GetData: function () { return mobilRates ; }, LoadData:LoadData}});
So before this route is loaded, it's going to call the LoadData
function in the factory. Once the data gets loaded, it resolves the promise so this LoadData
function will only get called once. Once the promise resolves, it will go ahead and load the view.
So now in your controller, whenever you want to get the data, all you have to do is call the function GetData
myApp.controller('smController', ['$scope', 'stadtMobilRates', function($scope, stadtMobilRates) { var stadtmobilRates = stadtMobilRates.GetData();});