为什么模态不能访问外部控制器?

时间:2014-08-14 09:22:27

标签: javascript angularjs angular-ui-bootstrap

说我的主要HTML:

<body ng-app="app" ng-controller="session as vmSession">
...
<!-- Modal will get created here -->
</body>

在我的模态中,我有一个链接:

<a ui-sref="siteManagement({ site: vmSession.user.site._id })" ng-click="$dismiss()">Example</a>

按钮没有正确的链接,而是指向根siteManagement页面,而不是登录用户的特定页面。 我注意到模态窗口是用ng-isolate-scope类创建的,那是什么阻止它工作?

3 个答案:

答案 0 :(得分:3)

使用$modal.open()时,您可以指定哪个$scope对象将继承模态控制器的范围:

$modal.open({
  templateUrl: 'modal.html',
  controller: 'modal',
  scope: $scope
});

如果缺少scope:,它将默认为$rootScope,这是会话控制器范围的父级,它无法访问您想要的数据的原因

答案 1 :(得分:1)

如果您不想按照其中一个答案中的建议使用resolve选项,则scope方法会有open选项。使用scope选项,您可以传递您希望模态范围所基于的任何范围。所以你可以做的是将控制器的范围作为scope属性传递,并让模态“看到”控制器看到的所有变量。

请注意$modal将创建您提供的范围的子范围(如果没有提供,则为$ rootScope),以免污染提供的范围。

答案 2 :(得分:0)

您可以将任何变量传递给模态控制器:

  $scope.openModal = function () {
    var modalInstance = $modal.open({
      templateUrl: '/templates/modal/yourModal.html',
      controller: YourModalCtrl,
      resolve: {
        values: function () {
          return {
            aValue: '123',
            anotherValue: {a: 'A', b: 'B'}
          };
        }
      }
    });

    modalInstance.result.then(function (result) {
        // ok result
    }, function (result) {
       // cancel result
    });
  };


var StepModalCtrl = function ($scope, $modalInstance, values) {
   var aValue = values.aValue;
   var anotherValue = values.anotherValue;

   $scope.doSomething = function () {
      console.log(aValue);
   };

   $scope.save = function () {          
       $modalInstance.close($scope.YourResult);
   };

   $scope.close = function () {
      $modalInstance.dismiss($scope.YourResult);
   };
};