AngularUI模态自定义范围

时间:2015-06-04 11:17:53

标签: angularjs angular-ui-bootstrap

我想为模态定义一个自定义范围(我不想使用依赖注入的原因)我在我的项目中使用,但每当我在{{1}中定义范围时我都会收到错误}。以下是我在AngularUI网站上的示例中创建的插件:http://plnkr.co/edit/rbtbpyqG7L39q1qYdHns

我尝试调试并看到$modal.open返回带有自定义范围的(modalOptions.scope || $rootScope),并且true(显然)没有定义true函数,例外情况是抛出。

有什么想法吗?

2 个答案:

答案 0 :(得分:2)

您必须传递范围实例:

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

如果您不想使用控制器的范围,您也可以传递自己的自定义范围,工作plnkr:

http://plnkr.co/edit/1GJTuVn45FgPC3jIgyHv?p=preview

答案 1 :(得分:0)

第一种方式

要将变量传递给模态,您可以这样做

var modalInstance = $modal.open({
      animation: $scope.animationsEnabled,
      templateUrl: 'myModalContent.html',
      controller: 'ModalInstanceCtrl',
      size: size,
      resolve: {
        items: function () {
          return $scope.items;
        },
        test: function(){
          return  $scope.test;   //This is the way
        }
      }
    });

在你的模态中你有这个

angular.module('ui.bootstrap.demo').controller('ModalInstanceCtrl', function ($scope, $modalInstance, items, test) {

  $scope.items = items;
  $scope.test = test;   // And here you have your variable in your modal

  console.log("Test: " + $scope.test)

  $scope.selected = {
    item: $scope.items[0]
  };

  $scope.ok = function () {
    $modalInstance.close($scope.selected.item);
  };

  $scope.cancel = function () {
    $modalInstance.dismiss('cancel');
  };
});

您可以在Plunker

中找到自己的示例

第二种方式

var modalInstance = $modal.open({
      animation: $scope.animationsEnabled,
      templateUrl: 'myModalContent.html',
      controller: 'ModalInstanceCtrl',
      size: size,
      scope: $scope,    // In this way
      resolve: {
        items: function () {
          return $scope.items;
        }
      }
    });

angular.module('ui.bootstrap.demo').controller('ModalInstanceCtrl', function ($scope, $modalInstance, items) {

  $scope.items = items;

  //You have available test and hello in modal
  console.log("Test 1: " + $scope.test);  
  console.log("Test 2: " + $scope.hello);

  $scope.selected = {
    item: $scope.items[0]
  };

  $scope.ok = function () {
    $modalInstance.close($scope.selected.item);
  };

  $scope.cancel = function () {
    $modalInstance.dismiss('cancel');
  };
});

Plunker第二种方式