angularjs - 通过控制器之间的数据 [英] angularjs - passing data between controllers

查看:150
本文介绍了angularjs - 通过控制器之间的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的模态建立一个角度应用程序,我想我的控制器之间通过一些数据来填充我的模态的视图。

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

我的主控制器JobListCtrl,当我点击应该调用模态的链接callReportModalData被触发。我使用的服务reportJobModalData来存储数据的传控制器之间

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>

下面的数据获取模态正确打印。不过,我不能访问控制器中的数据,即$ scope.test是空的,因为我只得到'测试:'登录控制台

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.

我在做什么错了?

非常感谢您的帮助。

推荐答案

尝试似乎被当值joblistctrl设定的时间服务变量应用的手表,reportjobctrl得到执行。

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

所以把这个code在reportjobctrl,让我知道结果。

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

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

function(new,old){
$scope.test=new;
});

这篇关于angularjs - 通过控制器之间的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆