user1828605 user1828605 - 6 months ago 14
AngularJS Question

How to pass data between controllers using directive?

I have a controller called

ClaimController
that stores various object such as
Patient
,
Prescriber
, and others. To keep things simple and to be able to reuse, I create another controller
PatientController
, and similarly other controllers for each component that I need. So, with that said, the snippet of the
ClaimController
looks like the following.

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


Then the
PatientController
looks like this:

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


The reason I have the object vm.Patient in both
PatientController
and
ClaimController
is so that I can use
PatientController
somewhere else and also associate Claim for the given Patient.

So,
PatientController
stores Patient object (or any changes to it). Then when Save button is clicked on
ClaimController
, the
vm.Patient
object should have
vm.Patient
object from
PatientController
. For this, I even created a directive:

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

link: function(scope, element, attrs){


}
}
}


The template:

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


But this is not working for me in the sense that
vm.Patient
in
ClaimController
object is always empty even when
vm.Patient
in
PatientController
contains data. so the data is not being passed. How can I fix this?

Answer

So, I ended up creating $watchCollection for the array or object that I'm watching instead of each field and saved the data in the Shared Service to be used by another components at later time. I removed the directive and kept it simple by putting $watchCollection in PatientController.

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

The template is now not dependent on ClaimController. Since all components have SharedService, the data can be retrieved by ClaimController when user hits the save button.

Comments