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.
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;
});
}
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With