AngularJS控制器之间共享代码/方法/功能
Sharing code/method/function between AngularJS 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;
});
};
我想在两个控制器中分享这两种方法。如何将$scope
从两个不同的控制器传递到我的共享方法?
谢谢你的帮助。
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;
});
}
Angularjs为我们提供了工厂和服务,工厂用于在控制器中使用的业务逻辑,服务应包含在多个地方使用的通用代码,即控制器或工厂。这就是在Angularjs应用程序中共享逻辑的方式。
乐于助人!
创建一个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;
}
相关文章:
- 有没有一种方法可以修改在使用javascript的媒体功能的媒体查询下创建的样式
- 使用多功能框在 chrome 扩展程序中包含内联自动填充功能的任何方法
- 基本阵列构造的功能方法
- AngularJS控制器之间共享代码/方法/功能
- 制作预制响应功能的最佳方法是什么
- 在触摸屏上实现<缩写>型功能的最干净方法
- 自动排序方法以附加功能
- 识别浏览器 HTML5 功能的推荐方法
- 将javascript方法功能分组到javascript“类”中
- 使用无状态功能组件与调用方法有什么区别
- JS扩展方法的功能
- javascript:在页面加载后执行该功能的最佳方法
- 通过SWT浏览器/ SWT浏览器功能从GWT应用程序调用Java方法
- 处理所需和可选功能参数的推荐方法
- 调用自定义API方法的功能
- 有没有更有效的方法来处理重复的功能
- 这是对象方法的内在功能
- 编辑JSON对象-寻找更好的功能方法
- 是否有任何JavaScript方法可以复制oracle的ADD_MONTH()功能?
- jQuery点击功能不同方法