简体   繁体   English

如何在angularJS中使跨控制器的$ scope操作代码干燥

[英]How to DRY up $scope-manipulating code across controllers in angularJS

Pardon if this question is a total blow-off... Just getting warmed-up into the world angularJS. 请原谅,如果这是一个完全的问题……刚开始热身于angularJS这个世界。

I have these two controllers: seekerController and wizardController ... 我有这两个控制器: seekerControllerwizardController ...

Inside the wizardController , I have a chat Scope object, and I have implemented a bunch of functions that are manipulating this chat Scope object. wizardController ,我有一个chat Scope对象,并且实现了一系列函数来操纵此chat Scope对象。

Going back to the other controller now, ( seekerController ), I discover that I need to have basically a direct replica of this chat Scope object and all the other functions manipulating it as I have inside wizardController 现在回到另一个控制器( seekerController ),我发现我基本上需要直接拥有此chat Scope对象的直接副本,并且需要像wizardController一样对所有其他函数进行操作。

The obvious way is just to copy all these into my other controller, and my work is done under a minute, but then I'll have a lot of repeated stuffs everywhere... 显而易见的方法是将所有这些复制到我的其他控制器中,我的工作在一分钟之内完成,但是随后到处都会有很多重复的东西……

So: I'm looking for a way where I can have this(the code) in a single place, but still be able to have access to this chat Scope object from both controllers, as well as all the other functions working seamlessly. 所以:我正在寻找一种方法,可以在一个地方拥有这个(代码),但是仍然能够从两个控制器以及所有其他无缝运行的函数访问此chat Scope对象。

Update - add code samples: 更新-添加代码示例:

//seekerController
angular.module('cg.seeker', [])
    .controller('SeekerController', ['$scope', 'seekerService', 'timeService', 'chatService', '$stateParams', 'toastr',
      function ($scope, seekerService, timeService, chatService, $stateParams, toastr) {
        ...
        // THE CHAT BUSINESS
        $scope.chat = { close: true };
        chatService.unreadCount(function(count){
          $scope.chat.unreadCount = count;
          $scope.$apply();
        });

        chatService.listDialogs( function (dialogList) {
          $scope.chat.dialogList = dialogList.items;
          $scope.$apply();
        } );

        $scope.endChat = function () {
          $scope.chat.close = true;
        }

        $scope.chatBox = function (dialogId, occupants_ids) {
          $scope.chat.opponentId = getOpponentId(occupants_ids);
          chatService.getMessages( dialogId, function (messageList) {
            $scope.chat.messages = messageList.items;
            $scope.chat.close = false;
            $scope.$apply();
          });
        }

        var getOpponentId = function (opponentId) {
          if(typeof(opponentId) != 'object') {
            return opponentId;
          } else {
            return opponentId.filter(function(x) { return x != $scope.seeker.chat_user.chat_id_string; })[0];
          }
        }

        $scope.sendMsg = function (opponentId) {
          var msg = {
            type: 'chat',
            body: $scope.chat.msg,
            extension: {
              save_to_history: 1,
            }
          };

          chatService.sendMsg(opponentId, msg);
          $scope.chat.msg = '';
        }

     ...

I now have an exact replica of the above code in a second controller WizardController . 现在,我在第二个控制器WizardController中具有上述代码的精确副本。 Exactly same, with no changes... and even a third controller have some of these, though not all. 完全一样,没有任何变化...甚至第三个控制器也有其中一些,尽管不是全部。

The next level of abstraction to angularjs controllers are 对angularjs控制器的下一个抽象层次是

  • Factory
  • Service 服务
  • Provider 提供者

You could use a service called maybe chatService which could contain the common code. 您可以使用一个名为chatService的服务,该服务可以包含通用代码。 You can inject the service into any controller which needs the common functionality and invoke the methods on the Service . 您可以将服务注入到需要通用功能的任何控制器中,并调用Service上的方法。

Do note that you could use any of the above three options even though I have mentioned just Service in the above statement. 请注意,即使我在上述声明中仅提到了Service ,也可以使用以上三个选项中的任何一个。

EDIT 1: 编辑1:

You could move the common parts of the code from Controller to Service. 您可以将代码的通用部分从Controller移到Service。 For example:- You could move the construction of msg object from controller to chatService . 例如:-您可以将msg对象的构造从控制器移动到chatService You controller would be simply - 您的控制器将很简单-

$scope.sendMsg = function (opponentId) {
      chatService.sendMsg(opponentId);
      $scope.chat.msg = '';
    }

And your chatService would be doing the hard-work. 而且您的chatService会努力工作。

    $chatService.sendMsg = function (opponentId) {
      var msg = {
        type: 'chat',
        body: $scope.chat.msg,
        extension: {
          save_to_history: 1,
        }
      };

      sendMsg(opponentId, msg);
    }

After simplifying the Controller s you could revisit to see if you could use only one controller instead of 3 as they seem to be doing similar function. 简化Controller之后,您可以重新查看是否只能使用一个控制器而不是3个,因为它们似乎在执行类似的功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM