使用$ broadcast - AngularJS在控制器之间传递变量

时间:2015-04-16 15:26:07

标签: angularjs

我有一个我从函数调用的模态,当我调用模态时,我想像这样传递一个URL:

ng-click="showModal('abc','testUrl')"

我想在控制器之间共享testUrl,所以我试试这个:

hmwsApp.controller('mainController', ['$scope', '$http', '$rootScope', 'ModalService', function($scope, $http, $rootScope, ModalService) {

$scope.showModal = function(modalUrl, imageUrl) {
  $rootScope.$broadcast('imageUrl', imageUrl); // <--- set global scope var
  ModalService.showModal({
    templateUrl: '/views/modals/' + modalUrl + '.html',
    controller: "ModalController"
  })
  .then(function(modal) {
    modal.element.modal();
    modal.close.then(function(result) {
      $scope.message = "Image show " + result;
    });
  });
};

}]);

然后在模态控制器中:

hmwsApp.controller('ModalController', function($scope, close) {

$scope.$on('imageUrl', function(response) {
  $scope.imageUrl = response; // <--- read global scope var
})

$scope.close = function(result) {
    close(result, 500); // close, but give 500ms for bootstrap to animate
};

});

我这样做的原因是我想引用模态中的URL,如下所示:

<div class="modal-content">
  <img src="{{ imageUrl }}">
</div>

但它根本不起作用,img src是空的,所以我想我错过了一些东西,但不确定是什么?有什么想法吗?

更新

还试过以下但仍然没有:

$scope.$on('imageUrl', function(events, args){
  console.log(args); // <--- empty
  $scope.imageUrl = args;
});

1 个答案:

答案 0 :(得分:1)

从我看到的情况来看,当您ModalController来电时,$rootScope.$broadcast尚未实例化。你应该在你显示模态之后做到这一点,否则它就不会存在&#34;存在&#34;用$scope.$on

拦截它