D
D
Dmitry2016-07-03 14:32:41
Angular
Dmitry, 2016-07-03 14:32:41

How to pass data from factory to controller?

Tell me, how can I transfer the data received via get from the factory, so that later it can be processed in the controller?

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

app.factory('loadData', ['$http', function($http) {
    return function() {
        $http.get('mydata.json').then(
            function(response) {
                // вот здесь как возвратить данные?
                return response
            },
            function(data) {
                // и здесь
                return data
        });
        // или их нужно возвращать здесь??
    };
}]);


app.controller('loadCtrl',['$scope', 'loadData', function($scope, loadData) {
    $scope.info = loadData();
    // а здесь я хочу обработать info
}]);

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexey Yarkov, 2016-07-03
@dkvasov

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

app.factory('serviceData', ['$http', function($http) {
    var self = this;

    self.loadData = function() {
        var promise = $http({
                url: 'mydata.json',
                method: 'GET',
                params: {},
                headers: {}
            })
            .then(function (response) {
                var response_data = angular.fromJson(response.data);
                return response_data;
            });
        return promise;
    };

    return self;
}]);


app.controller('loadCtrl',['$scope', 'serviceData', function($scope, serviceData) {
    // а здесь я хочу обработать info
    serviceData.loadData()
        .then(function (response_data) {
            $scope.info = response_data;
        });;
}]);

S
Sergey, 2016-07-03
Protko @Fesor

via get data from the factory

So, let's understand from the beginning what a "factory" is. A factory is a way to get services. That is, this is the thing that is called by the angular dependency container when the service is created, and that's it.
So let's call it a service.
Further. We read the documentation regarding such a thing as promises (maybe not even in the context of angular). As a js developer, you must understand what an event loop is, why all interaction with the outside world should be asynchronous, and how to live with it (callbacks, promises, yield and async/await).
Further. Try to use router resolvers to get data. Then the data will come ready.
Well, the last. Avoid $scope and controllers. Use components. Now it's 2016 and the current version of Angular is 1.5, and the second one is on the way. Do not use teaching materials that are 5 years old.
just a couple of weeks ago, they finally updated the official Angular tutorials for a modern approach, taking into account the best practices that have been developed:https://github.com/angular/angular-phonecat

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question