简体   繁体   中英

How to: From service to factory, or a service without $scope in it?

I have an Angular app where I am displaying the posts of a WP account, I am using $scope in the service but according to some articles, putting $scope in a service is not a proper way.

And also someone ask me to do a factory instead.

I am trying to not use $scope and to create a factory but my app goes down once I try.

Here is a Plunker where I recreate the full action of my app.

And here part of the code you will see in that Plunker

.controller('NewsCtrl', function($scope,
                                 FreshlyPressed, $stateParams) {
  $scope.posts = [];
  $scope.doRefresh = function() {
    $scope.posts = FreshlyPressed.getBlogs($scope);
    $scope.$broadcast('scroll.refreshComplete');
  }
  $scope.doRefresh();
})

.service('FreshlyPressed', function($http) {
  return {
    getBlogs: function($scope) {
      $scope.postsURL = 'http://urbanetradio.com/wp-json/posts?_jsonp=JSON_CALLBACK';
      $http.jsonp($scope.postsURL).success(function(data, status, headers, config) {
        $scope.posts = data;
        console.log(angular.toJson($scope.posts, 'pretty'));
      }).error(function(data, status_headers, config) {
          console.log('error')
      });
    },
    getPostById: function(postId) {
      var url ='http://urbanetradio.com/wp-json/posts/'+ postId;
      return $http.get(url);
    }
  }
})

.controller('PostDetailCtrl', function($scope, $stateParams, $sce, FreshlyPressed) {

    var postId = $stateParams.postId,

    FreshlyPressed.getPostById(postId).success(function(response){
       console.log(response);
       $scope.post = response;
    });

    // Marks src as safe
    $scope.trustSrc = function(src) {
       return $sce.trustAsHtml(src);
    };
}); 

so there you can see .service('FreshlyPressed') thats what I want to use as a Factory, or could be the same service but without the usage of $scope

The PostDetailCtrl and FreshlyPressed.getPostById is the right way. Here's how you'd modify getBlogs and NewsCtrl :

.controller('NewsCtrl', function($scope, FreshlyPressed, $stateParams) {
  $scope.posts = [];
  $scope.doRefresh = function() {
    FreshlyPressed.getBlogs().success(function(blogs) {
      $scope.posts = blogs;
      $scope.$broadcast('scroll.refreshComplete');
    }).error(function() {
      console.log('error');
    });
  }
  $scope.doRefresh();
})


.service('FreshlyPressed', function($http) {
  return {
    getBlogs: function() {
      return $http.jsonp('http://urbanetradio.com/wp-json/posts?_jsonp=JSON_CALLBACK');
    },
    getPostById: function(postId) {
      var url ='http://urbanetradio.com/wp-json/posts/'+ postId;
      return $http.get(url);
    }
  }
})

I think that you didn't understand well the reason why you create factories, so I'll begin my post describing factories.

A factory is a part of your app that should get an information for you, like a server side helper class. It shouldn't know whether it works for another factory, a provider, or a controller. For example, here you should create a function which returns the Promise* or the information for the web service.

My suggestion for you is to refactor according to this:

 .controller('NewsCtrl', function($scope, $ionicLoading, FreshlyPressed, $stateParams) { $scope.posts = []; $scope.doRefresh = function() { FreshlyPressed.getBlogs().success(function(res){ $scope.posts=angular.toJson(res); }); /*Your'e here broadcasting to no one. you should broadcast to $rootScope.. so all the inheritant scopes will get the messege.. and i can't see here the listening event either.*/ $scope.$broadcast('scroll.refreshComplete'); } /*Initializing the posts*/ $scope.doRefresh(); }) .service('FreshlyPressed', function($http) { return { getBlogs: function() { var postsURL = 'http://urbanetradio.com/wp-json/posts?_jsonp=JSON_CALLBACK'; return $http.jsonp(postsURL); }, getPostById: function(postId) { var url ='http://urbanetradio.com/wp-json/posts/'+ postId; return $http.get(url); } } }) .controller('PostDetailCtrl', function($scope, $stateParams, $sce, FreshlyPressed) { var postId = $stateParams.postId, siteId = $stateParams.siteId; console.log( $stateParams); FreshlyPressed.getPostById(postId).success(function(response){ console.log(response); $scope.post = response; }); // Marks src as safe $scope.trustSrc = function(src) { return $sce.trustAsHtml(src); }; }); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM