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
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/
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