Question

I need to handle a click on a tag that enables the opening of a popover.

I try to figure out the best way to do this with angularjs and naturally used hg-click.

<div ng-repeat="photo in stage.photos" 
ng-click="openPopoverImageViewer($(this))"
>

$scope.openPopoverImageViewer = function  (source) {
alert("openPopoverImageViewer "+source);
}

The issue is that I cannot manage to pass the $(this) to it.

  1. Q1) How to pass the jQuery element?

  2. Q2) In addition, ng-click sounds to require the function being part of the controller: is it possible to invoke a function in the partial instead?

Was it helpful?

Solution

You need to stop "thinking in jQuery" :) Like @oori says, you can pass in photo. Or better yet, create a custom directive. Directives is the way to go when you need new functionality in your dom, like an element that you can click to open an overlay. For example:

app.directive('popOver', function() {
  return {
    restrict: 'AE',
    transclude: true,
    templateUrl: 'popOverTemplate.html',
    link: function (scope) {
      scope.openOverlay = function () {
        alert("Open overlay image!");
      }
    }
  };
});

You can then use this as a custom elemen <pop-over> or as an attribute on regular HTML elements. Here is a plunker to demonstrate:

http://plnkr.co/edit/P1evI7xSMGb1f7aunh3G?p=preview

Update: Just to explain transclusion: When you say that the directive should allow transclusion (transclude:true), you say that the contents of the tag should be sent on to the directive.

So, say you write <pop-over><span>This will be passed on</span></pop-over>, then the span with "This will be passed on" is sent to the directive, and inserted wherever you put your ng-transclude element in your template. So if your pop-over template looks something like this:

<div>
    <ng-transclude/>
</div>

Then your resulting DOM after the template has compiled will look like this:

<div>
     <span>This will be passed on</span>
</div>

OTHER TIPS

Pass it "photo"

<div ng-repeat="photo in stage.photos"  ng-click="openPopoverImageViewer(photo)">

or the current $index

<div ng-repeat="photo in stage.photos"  ng-click="openPopoverImageViewer($index)">
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top