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

标签 javascript angularjs

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

相关文章:

javascript - 获取隐藏类型值的 span id 值

javascript - Frida - 访问具有所需类型的类属性

javascript - 如何在 Firebase 中使用 equalsTo()?

javascript - 在这种情况下如何扩展asp.net应用程序

javascript - 如何将单选按钮组重置为特定值

javascript - 为什么 ctx.drawImage 只是将视频元素的一部分绘制到 Canvas 上?

css - AngularJS 指令观察父级高度变化

javascript - 在 ng-view 之外更新 HTML 元素

javascript - ng-repeat动画完成回调

javascript - 我怎样才能共享范围并在 Angular Directive(指令)中传递数据