简体   繁体   中英

How to catch click event on remote loaded data and displayed with angularJS

I would like to include html data loaded from ajax request and trigger click event on images in my html data. I understand that this is wrong in SPA world but I need displays data from wysiwyg editor ...

This is code refactored from version with 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 = "";
                    }
             });

But it does not function because images isn't in DOM when I trigger click event on them... What is the best practice to solve this issue?

Thanks!

I'm not exactly sure what viewData represents, but I think you are going about this in the wrong way.

When using angular, you shouldn't be loading html from the server (unless it's a template, via templateUrl ).

Instead your server should return data which you then display using a template.

So for images, for example, you might return something like this from your server:

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

Then your html could have something like the following:

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

And your controller:

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

  $scope.showInGallery = function(image){

    //your gallery code here.

  }
});

I would suggest reading more about angular and S (ingle) P (age) A (pplication)s, as you are trying to use a framework in a way other than how it was designed. This means you'll hit lots of stumbling blocks and won't benefit from the power of the great community that surrounds it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM