angularjs - passing data between controllers

2019-06-14 05:14发布

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

2条回答
冷血范
3楼-- · 2019-06-14 06:00

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;
});
查看更多
登录 后发表回答