【问题标题】:How to catch click event on remote loaded data and displayed with angularJS如何捕获远程加载数据上的点击事件并使用 angularJS 显示
【发布时间】:2014-03-10 16:15:17
【问题描述】:

我想包含从 ajax 请求加载的 html 数据,并在我的 html 数据中触发图像的点击事件。我知道这在 SPA 世界中是错误的,但我需要显示来自 wysiwyg 编辑器的数据...

这是用 jQuery 重构的代码:

          $http.get('Help/Help/GetHelp', {
                params: {
                    helpId: contentKey
                }
            })
                .success(function(data) {
                    if (data.success) {

                        // viewData is html from wysiwyg editor
                        $scope.viewData = data.viewData;

                        // HERE is problem because now images isn't in DOM. This is too early
                        angular.element('div#content').find('img').click(function () {
                            // Show image in gallery
                        });
                    } else {
                        $scope.viewData = "";
                    }
             });

但它不起作用,因为当我在它们上触发点击事件时,图像不在 DOM 中......解决这个问题的最佳做法是什么?

谢谢!

【问题讨论】:

标签: javascript html angularjs


【解决方案1】:

我不太确定viewData 代表什么,但我认为你的做法是错误的。

使用 Angular 时,不应从服务器加载 html(除非它是模板,通过 templateUrl)。

相反,您的服务器应该返回您使用模板显示的数据。

例如,对于图像,您可能会从服务器返回如下内容:

[
  {
    name: 'image1',
    url: 'some/url.jpg'
  },
  {
    name: 'image two',
    url: 'some/other/url.jpg'
  }
]

那么你的 html 可能有如下内容:

  <img ng-src="image.url" 
       ng-click="showInGallery(image)" 
       alt="{{image.name}}" 
       ng-repeat="image in images"/>

还有你的控制器:

app.controller('ImageController', function($scope, imageService){
  imageService.getImages().then( function(images){
    $scope.images = images
  });

  $scope.showInGallery = function(image){

    //your gallery code here.

  }
});

我建议您阅读更多有关 angular 和 S(ingle)P(age)A(pplication)s 的信息,因为您正在尝试以不同于设计方式的方式使用框架。这意味着您会遇到很多绊脚石,并且不会从围绕它的伟大社区的力量中受益。

【讨论】:

  • 嗨,Ed,我了解什么是 SPA,但请尝试想象一下您在所见即所得编辑器中显示编辑数据的应用程序......此用户编辑的数据显示在我们的 Web 和移动应用程序上。我无法使用 AngularJS 指令保存数据。需要像我基本上用 jQuery 做的事情 - 初始化 DOM 的某些部分中的所有图像元素。
  • 我可能没有正确理解您,但如果您将 HTML 添加到已由 angular 处理的元素中,您可能需要使用 angular 的 $compile 手动将额外的 html 链接到范围创建一个链接函数,然后将$scope 传递给生成的链接函数。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-08-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多