AngularJS控制器之间共享代码/方法/功能

Sharing code/method/function between AngularJS controllers

本文关键字:方法 功能 代码 共享 控制器 之间 AngularJS      更新时间:2024-06-01

我到处找过了。人们谈论的主要是使用工厂在控制器之间共享数据。但在我的情况下,我想在控制器之间共享代码逻辑。

$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;
}