S
S
Sapphiron5322015-07-23 23:14:13
Angular
Sapphiron532, 2015-07-23 23:14:13

How to make an http request to the factory?

Hello.
Started rewriting the project while it was at an early stage, but ran into difficulty.
The controller has a function that is called by clicking on the link, receives json, which it puts into an array. Further, this data is displayed on the page using ng-repeat and the directive.

$scope.getFiles = function(id) {
  $element.find("files").remove(); // очистка div'a
  $http.get("http://тут_урл").success(function(response) {
      $scope.files = response;
  });
    };

Directive
app.directive("file", function() {

    return {
  restrict : "E",
  scope : true,
  controller : function($scope, $element) {
      $scope.fileName = $scope.file.fileName;
      $scope.fileContent = $scope.file.content;
  },

  link : function(scope, el, attr) {
      scope.fileName = scope.fileName;
      scope.fileContent = scope.fileContent;
  },

  template : "<div id=\"{{fileName}}\"><h3 class='title'>name: {{fileName}}</h3> \
 <pre class=\"java\">{{fileContent}}</pre></div>"
    }
});

I'm just trying to put the function in a factory and assign the result to a variable.
angular.module("myApp").factory("gistsFactory", function( $http) {
    var service = {};

    service.getFiles = function(id) {
//	    $element.find("files").remove();
      $http.get("http://тут_урл").success(function(response) {
     return response;
     });
    }
    return service;
})

//В контроллере меняю на вызов функции
 $scope.getFiles = function(id) {
      $scope.files = gistsFactory.getFiles(id);
 };

But if the first option works, then when you call it from the factory, the data comes, but it is not displayed on the page, although in both cases I assign data to the same variable inside the same function, which simply turns out in different places.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey, 2015-07-23
Protko @Fesor

to the factory

First, figure out what a factory is. A factory is such a thing that creates something, for example, collects and instantiates some kind of service.
And you take a closer look, you do not return anything in the getFiles method of your service. Promise must be returned.
.factory("gistsFactory", function( $http, $q) {

    return {
         getFiles: function(id) {
              return $http.get("http://тут_урл").then(function(response) {
                   return response.data;
              }, function (reason) {
                   return $q.reject(reason);
              });
    };
})

ps don't use $scope in controllers, and yes, read the documentation.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question