$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;
});
};
我想在两个控制器中分享这两种方法。如何将$scope
从两个不同的控制器传递到我的共享方法?
感谢您的帮助。
答案 0 :(得分:4)
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);
}
}
然后在您的控制器中,您可以调用这些方法
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;
});
}
答案 1 :(得分:3)
创建一个postService,将其注入所需的所有控制器。然后让控制器管理$ scope更改并从您的服务中获取内容。下面应该开始......
app.factory('postService', function() {
var updatePost = function...
var postComment = function ...
}
app.controller('whateverController', function($scope, postService) {
$scope.post = postService.updatePost();
}
更新 - 如何将$ scope元素绑定到服务的值
的示例HTML:
<div>{{comment_error_messages()}}</div>
在您的控制器中:
$scope.comment_error_messages = function () {
return postService.getErrorMessages()
};
您的服务:
var getErrorMessages = function () {
...
return val;
}
答案 2 :(得分:3)
Angularjs为我们提供了工厂和服务,工厂用于控制器中的业务逻辑,服务应包含在多个地方使用的通用代码,即控制器或工厂。这是在Angularjs app中共享逻辑的方式。
快乐帮助!