无法将作用域传递给Angular对话框

6

我正在使用Angular显示一个图片列表。

当用户点击某一张图片时,我想显示一个带有该图片以及更多信息的对话框。

因此,在打开模态框时,我需要传递$scope或至少传递一个图片参数。

注意:我正在使用ngDialog来实现弹出窗口。

  application.controller('ImageController', function ImageController($scope, ImageService, ngDialog) {

    $scope.model = {
      images: [],
      loading: false
    }

    var load = function () {
      $scope.model.loading = true;
      ImageService.GetList($scope.model.pages.instagram)
        .success(function (data, status, headers, config) {
          $scope.model.images = $scope.model.images.concat(data.Images)
        })
        .error(function (data, status, headers, config) { })
        .finally(function () {
          $scope.model.loading = false
        });;
    }

    $scope.open = function (image) {
      ngDialog.open({
        template: '<p>my template {{image.Key}} </p>',
        plain: true,
        scope: $scope
      });
    };


    load();

  });

  <div data-ng-app="Application" data-ng-controller="ImageController">
    <div data-ng-repeat='image in model.images'>
    <img src="{{image.Url}}" alt="" data-ng-click="open(image)"/>
  </div>

点击后显示图像并打开对话框...

然而,不知何故,我无法在模板中访问作用域。

下面的内容是有效的:

    $scope.open = function (image) {
      ngDialog.open({
        template: '<p>my template' + image.Key + '</p>',
        plain: true
      });
    };

但是这个并不起作用:
    $scope.open = function (image) {
      ngDialog.open({
        template: '<p>my template {{image.Key}} </p>',
        plain: true,
        scope: $scope
      });
    };

有没有人知道为什么?

我一直没能弄清楚这个问题。


如果您将对话框的HTML作为ImageController的子元素包含在内,那么您就可以访问控制器的作用域。另一种方法是使用$broadcast/$emit向下和向上推送数据。 - SoluableNonagon
当你说“如果你将对话框的HTML作为ImageController的子元素包含在内”,你是指我的示例1吗?因为那个是有效的... - Miguel Moura
我通过阅读以下内容创建了我的第二个示例:https://github.com/likeastore/ngDialog#scope-object,所以我不确定我错过了什么... - Miguel Moura
2个回答

10

将您的打开方法更改为以下方法...

  $scope.open = function (image) {
      var newScope = $scope.$new();
      newScope.image = image;
      ngDialog.open({
        template: '<p>my template {{image.Key}} </p>',
        plain: true,
        scope: newScope
      });
    };

这应该会起作用...


1
我觉得最好的方法是不使用作用域,而是使用数据属性:
 $scope.open = function (image) {          
                  ngDialog.openConfirm({
                  template: 'views/alertTemplate.html'
                  showClose: false,
                  data: {
                    image: image,
                  }
                });  
            }

在你的模板文件中:
<div class="alert-dialog-container">
  <div class="alert-dialog-body">
    <p ng-bind-html="ngDialogData.image"></p>
  </div>
  <div class="alert-dialog-footer">
    <button ng-click="confirm()">OK</button>
  </div>
</div>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接