0

I am building an angular app using modals and I'd like to pass some data between my controllers to populate my modal view.

My main controller is JobListCtrl and callReportModalData is triggered when I click on the link supposed to call the modal. I use the service reportJobModalData to store the data an pass it between controllers.

var myApp = angular.module('myApp', []);


myApp.controller('JobListCtrl', ['$scope', '$element', '$http', '$log', 'reportJobModalData', function ($scope, $element, $http, $log, reportJobModalData) {

    $scope.reportJobModalData = reportJobModalData;

    $scope.callReportModal = function(test){
        reportJobModalData.test = test;
    }

}]);

myApp.service('reportJobModalData', function(){
    this.test = '';

});

My modal controller and directive are defined as follow:

myApp.controller('reportJobCtrl', function ($rootScope, $scope, $http, $log, reportJobModalData) {
    $scope.$log = $log;
    $scope.reportJobModalData = reportJobModalData;

    $scope.test = reportJobModalData.test;
    $log.info('test: ' + reportJobModalData.test);


});

myApp.directive('sjReportJobModal', ['$rootScope', '$log', '$http', 'reportJobModalData', function ($rootScope, $log, $http, reportJobModalData) {
  return {
    restrict: 'E',

    templateUrl: 'report-job-modal-tpl',

    replace: true,

    transclude: true,

    link: function (scope) {
    }
  };
}]);

and the template I use is this one:

<div class="modal fade" id="reportJobModal" tabindex="-1" role="dialog" aria-labelledby="reportJobModalLabel" aria-hidden="true" ng-controller="reportJobCtrl">
  <div class="modal-content ease">
    <section>
      {{ reportJobModalData.test }}
    </section>
  </div>
  <div class="modal-overlay ease" data-dismiss="modal"></div>
</div>

Here the data get printed properly on the modal. However I cannot access the data in the controller, i.e. $scope.test is empty as I only get 'test :' logged on the console.

What am I doing wrong?

Thanks a lot for your help

Spearfisher
  • 8,445
  • 19
  • 70
  • 124

2 Answers2

0

try applying a watch on the service variable it seems by the time when the value is set in joblistctrl, your reportjobctrl gets executed.

so place this code in reportjobctrl and let me know the results

$scope.$watch(function(){
return reportJobModalData.test},

function(new,old){
$scope.test=new;
});
Rishul Matta
  • 3,383
  • 5
  • 23
  • 29
  • ok you're right! Thanks!! $scope.test gets set when the page loads so there's no value yet as no link has been clicked. How can I make sure it is only set when the modal is call? – Spearfisher Mar 14 '14 at 14:16
  • set the value of reportJobModalData.test only when you call the modal perhaps in the link function of your directive this will invoke the watch too. If it helps please do select as answer. thanks – Rishul Matta Mar 14 '14 at 14:30