gpt4 book ai didi

javascript - 在 AngularJS Controller 之间共享代码/方法/函数

转载 作者:搜寻专家 更新时间:2023-11-01 05:00:32 28 4
gpt4 key购买 nike

我四处寻找。人们主要谈论使用工厂在 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com