F
F
Fedor2014-10-31 09:54:42
Angular
Fedor, 2014-10-31 09:54:42

How to pass data to controller after service-a initialization?

Tell me how to pass the received data to the controller (or to the view)?
given
//main.js

angular
  .module('app', []);

angular
  .module('app')
  .factory('myService', myService);

myService.$inject = ['$http'];

function myService($http){
  var result = {
      data = []
    };
  var init = function(){
    $http.get('/api/data')
      .success(function(data, status){
        if (status == 200) {
               result.data = data;
                       } 
         });
  };
  init();
  return result;
};

angular
  .module('app')
  .controller('main', mnCntr);
mnCntr.$inject = ['myService','$scope'];
function mnCntr(myService,$scope){
  $scope.somedata = myService.data;
};

//index.html
<html lang="en" ng-app="app">
<head>
</head>
<body >
  <div ng-controller='main'>
    <p>{{somedata}}</p>
  </div>
</body>
<script src="./libs/angular/angular.min.js"></script>
<script src="./js/main.js"></script>
</html>

in theory, data is loaded into the service, the controller must transfer them to the view
. Of course, this example does not show anything. receives data by promise,
how to do it correctly so that it shows with the preservation of the scheme of work?
Or is this a bad design? how to do it better then? :)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey, 2014-10-31
@Filoret256

$http returns a promise.

function serviceFactory($http) {
    
    return function () {
        $http.get('/api/data').then(function (response) {
             return response.data;
        }
    }
}

function mainController($scope, myService) {
    myService().then(data) {
        $scope.data = data;
    }
}

D
digrabok, 2014-10-31
@digrabok

Something like this:

(function () {
    'use strict';

    angular.module('app', [])
        .service('myResource', ['$resource', function($resource) {
            return $resource('/api/data');
        }])
        .controller('main', ['$scope', 'myResource', function($scope, myResource) {
            $scope.somedata = myResource.query();
        }])

})();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question