Answer the question
In order to leave comments, you need to log in
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;
};
<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>
Answer the question
In order to leave comments, you need to log in
$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;
}
}
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 questionAsk a Question
731 491 924 answers to any question