javascript - How to properly use custom service in AngularJS -


I am trying to transfer my controller argument to a service. I have added DataService and injected $ http I then loads the loadData () method JSON. I have injected this service into a test controller and call it a function, but it does not work. The only simple argument worked properly with a controller should I improve? :)

  var app = angular Module ('testap', []); App.controller ('Test Controller', Test Controller); App.service ('DataService', data service); Function Test Controller {var vm = this; Vm.personalInfo = DataService.loadData (); } Function data service ($ http) {var store = this; Store.personInfo = []; Store.loadData = function {$ http.get ('data.json') .success (data) {store.personInfo = data;}) .error (function () {store.personInfo = "error occurred" ;}); Return Store. PersonInfo; }; }  

My view looks as simple as this:

 body ng-app = "TestApp" ng-controller = "Test Controller "& Gt; & Lt; H1 & gt; Hello Plunker! & Lt; / H1> & Lt; P ng-repeat = "item in test.personalInfo" ng-bind = "item.firstname" & gt; & Lt; / P & gt; & Lt; Script Data - Security = "angular.js@1.2.25" Data-save = "1.2.25" src = "https://code.angularjs.org/1.2.25/angular.js" & gt; & Lt; / Script & gt; & Lt; Script src = "script.js" & gt; & Lt; / Script & gt; & Lt; / Body & gt;    

returning store.loadData to your code Come with the pre-undetered answer backend, then use this code:

  var app = angular Module ('testap', []); App.controller ('Test Controller', Test Controller); App.service ('DataService', data service); Function Test Controller {var vm = this; DataService.loadData () Then (function (data) {vm.personalInfo = data.data}). Hold (function (error) {console.log (err)}}} function data service ($ http) {var store = this; Store.personInfo = []; Store.loadData = function () {return $ http.get ( 'Data.json')}}}  

Comments