angularjs - passing data between controllers

蹲街弑〆低调 提交于 2019-12-10 12:17:44

问题


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


回答1:


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;
});



回答2:


You need to use $broadcast

Check the below url:

http://onehungrymind.com/angularjs-communicating-between-controllers/

http://blog.edweng.com/2013/06/10/angularjs-sharing-variables-between-controllers/



来源:https://stackoverflow.com/questions/22407198/angularjs-passing-data-between-controllers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!