如何使用指令在控制器之间传递数据?

How to pass data between controllers using directive?

我有一个名为 ClaimController 的控制器,它存储各种对象,例如 PatientPrescriber 等。为了使事情简单并能够重用,我创建了另一个控制器 PatientController,并为我需要的每个组件创建了类似的其他控制器。因此,话虽如此,ClaimController 的代码片段如下所示。

testApp.controller('ClaimController', [
   '$scope', ..., 
   function($scope, ...){
       var vm = this;
       vm.Patient = {}
       .....
}]);

然后 PatientController 看起来像这样:

testApp.controller('PatientController', [
    '$scope', ... , 
    function ($scope, .. ){
          var vm = this; 
          vm.Patient = {};
          ....         
}]);

我在 PatientControllerClaimController 中都有对象 vm.Patient 的原因是我可以在其他地方使用 PatientController 并关联给定患者的 Claim .

因此,PatientController存储 Patient 对象(或对其进行的任何更改)。然后,当单击 ClaimController 上的保存按钮时,vm.Patient 对象应该具有来自 PatientControllervm.Patient 个对象。为此,我什至创建了一个指令:

testApp.directive('patientInfo', function(){
      return {
           restrict: 'A',
           transclude: false,
           templateUrl: 'path/to/template', 
           controller: 'PatientController',
           controllerAs: 'patCtrl',
           scope: {
               patient: '='
           },

           link: function(scope, element, attrs){


           }
      }
}

模板:

<div ng-controller="ClaimController as ctrl">
    <div patient-info patient="ctrl.Patient"></div>
</div>

但这对我不起作用,因为 ClaimController 中的 vm.Patient 对象始终为空,即使 PatientController 中的 vm.Patient 包含数据。所以数据没有被传递。我怎样才能解决这个问题?

您的代码几乎是正确的,只有一处错误 code.You 需要使用数据方法而不是 "patient-info patient"

<div ng-controller="ClaimController as ctrl">
<div data-method="ctrl.Patient"></div>
</div>

因此,我最终为我正在观察的数组或对象而不是每个字段创建了 $watchCollection,并将数据保存在共享服务中以供其他组件稍后使用。我删除了该指令并通过将 $watchCollection 放在 PatientController 中使其保持简单。

$scope.$watchCollection('patCtrl.Patient', function(newVal, oldVal){
          SharedService.setPatient(newVal);
});

模板现在不依赖于 ClaimController。由于所有组件都有 SharedService,当用户点击 save 按钮时,可以通过 ClaimController 检索数据。