【问题标题】:Sharing data between controller and angular-bootstrap $modal在控制器和 angular-bootstrap $modal 之间共享数据
【发布时间】:2014-07-30 21:21:15
【问题描述】:

我正在使用 angular-bootstrap $modal,但我对如何在控制器和模态之间共享数据有疑问。

控制器:

app.controller 'MainController', ($scope, $templateCache) ->      
  $scope.openModal = ->
    modal = $modal.open(
      template: $templateCache.get('modal.html')
      controller: modalController
      size: 'sm'
      resolve:
        repository: ->
          $scope.repository
    )

模态:

modalController = ($scope, $modalInstance, repository) ->
  $scope.repository = repository

  $scope.update = (other_repo) ->
    $scope.repository = other_repo  
    $modalInstance.dismiss('cancel')

此时,我希望 MainController 中的 $scope.repository 在从模态更改时更新,但事实并非如此。

我错过了什么?

谢谢

【问题讨论】:

    标签: angularjs angular-ui-bootstrap


    【解决方案1】:

    模态控制器的作用域与打开模态的控制器不同。要在对话框关闭后从对话框中取回一些数据,您应该从结果承诺中获取它,如the documentation 中的示例所示:

    modal = $modal.open(...);
    
    modal.result.then(function (otherRepo) {
      $scope.repository = otherRepo;
    }
    

    【讨论】:

      【解决方案2】:

      如果你没有将控制器的作用域传递给 $modal,它会创建一个新的,原型继承自 $rootScope:var modalScope = (modalOptions.scope || $rootScope).$new();,并且从这个控制器没有连接到开启者的控制器作用域。 但是您可以传递到打开它的控制器的模态范围:

        $scope.open = function (size) {
          var modalInstance = $modal.open({
            templateUrl: 'myModalContent.html',
            controller: ModalInstanceCtrl,
            size: size,
            scope: $scope
          });
      

      这一次,ModalInstanceCtrl 中的作用域将继承父控制器的作用域,所有更改都将反映在 opener 控制器的作用域中。

      Look at this plunker (it's slightly changed sample from Bootstrap-UI) selected 来自开启器范围的对象以模式更新,此更新立即反映在 ModalDemoCtrl 控制器的视图中。

      【讨论】:

      • 这在 OP 的情况下不起作用,因为他不修改来自控制器范围的对象:他直接写入子范围。所以控制器范围将保持不变。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-30
      • 2015-12-15
      • 2014-03-22
      • 1970-01-01
      • 2013-08-14
      • 1970-01-01
      相关资源
      最近更新 更多