Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sharing code/method/function between AngularJS controllers

I have searched around. People talked mostly about sharing data between controllers using factory. But in my case I would like to share code logic between controllers.

$scope.updatePost = function(){
  $http.get(sprintf("/posts/%s.json", post.id)).
  success(function(data, status, headers, config) {
    $scope.post = data;
  })
};

$scope.postComment = function(){
  if(!$scope.post.logged){
    window.location.href = "/users/sign_in";
  }

  var data = { post_id: $scope.post.id, content: $scope.content };
  $http.post("/comments", data).
  success(function(data, status, headers, config) {
    $scope.comment_error_messages = [];
    $scope.updatePost();
  }).error(function(data, status, headers, config) {
    $scope.comment_error_messages = data.errors;
 });
}; 

I would like to share these two methods in two controllers. And how do I pass in the $scope from two different controller to my share methods?

Thanks for any help.

like image 609
icn Avatar asked Dec 25 '22 22:12

icn


2 Answers

app.factory('postService', postService);

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

function postService($http) {
  var updatePost = function(post) {
    return $http.get(sprintf("/posts/%s.json", post.id))
  }

  var postComment = function(post, content) {
    var data = { post_id: post.id, content: content };
    return $http.post("/comments", data);
  }
}

And then in your controller(s), you could call these methods

app.controller('myController', myController);

myController.$inject = ['$scope', 'postService'];

function myController($scope, postService) {
  $scope.updatePost = function() {
     postService
       .updatePost($scope.post)
       .success(function(data, status, headers, config) {
          $scope.post = data;
       });
  }

  $scope.postComment = function(){
    // you could move this to the postService if you wanted
    if(!$scope.post.logged){
      window.location.href = "/users/sign_in";
    }

    postService
      .postComment($scope.post, $scope.content)
      .success(function(data, status, headers, config) {
         $scope.comment_error_messages = [];
         $scope.updatePost();
      })
      .error(function(data, status, headers, config) {
        $scope.comment_error_messages = data.errors;
    });
}
like image 151
Tom Avatar answered Dec 28 '22 09:12

Tom


Angularjs has provided us with Factories and Servicece, Factories are for business logic to be used in controllers and Services should contain common code that is to be used in multiple places i.e controllers or factories. This is the way how logic is to be shared inside Angularjs app.

Happy Helping!

like image 27
Zeeshan Hassan Memon Avatar answered Dec 28 '22 10:12

Zeeshan Hassan Memon