我四处寻找。人们主要谈论使用工厂在 Controller 之间共享数据。但就我而言,我想在 Controller 之间共享代码逻辑。
$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;
});
};
我想在两个 Controller 中分享这两个方法。我如何将 $scope
从两个不同的 Controller 传递到我的共享方法?
感谢您的帮助。
最佳答案
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);
}
}
然后在您的 Controller 中,您可以调用这些方法
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;
});
}
关于javascript - 在 AngularJS Controller 之间共享代码/方法/函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28750210/