I'm trying to move my controller logic to a service. I've added DataService and injected $http. Then loadData() method returns JSON. I've injected this service into a TestController and called mentioned function, but it doesn't work. The same simple logic worked correctly from a controller. What should I improve? :)
var app = angular.module('TestApp', []);
app.controller('TestController', TestController);
app.service('DataService', DataService);
function TestController(DataService) {
var vm = this;
vm.personalInfo = DataService.loadData();
}
function DataService($http) {
var store = this;
store.personInfo = [];
store.loadData = function(){
$http.get('data.json')
.success(function(data){
store.personInfo = data;
})
.error(function(){
store.personInfo = "Error occured";
});
return store.personInfo;
};
}
My view looks as easy as that:
<body ng-app="TestApp" ng-controller="TestController as test">
<h1>Hello Plunker!</h1>
<p ng-repeat="item in test.personalInfo" ng-bind="item.firstname"></p>
<script data-require="[email protected]" data-semver="1.2.25" src="https://code.angularjs.org/1.2.25/angular.js"></script>
<script src="script.js"></script>
</body>
loadDatato return anything but[], then it won't because the call to$httpis asynchronous. You need to set yourvm.personalInfowhen thesuccess/errorcallback is called.