简体   繁体   中英

How to pass “this” with ng-click?

I think I have done this before but I forgot how to do it. Here is what I want to accomplish:

In the html, I have this setup:

<md-card ng-repeat="card in cards" data-link="{{card.link}}" ng-click="showCardDes(this)">

In my Angular script, I set this up:

  $scope.showCardDes = function(e) {
    var tempUrl = $(e).attr('data-link');
    $mdDialog.show({
      controller: DialogController,
      templateUrl: tempUrl,
    });
  };

I also tried in html:

<md-card ng-repeat="card in cards" ng-click="showCardDes({{card.link}})">

and in my Angular script:

  $scope.showCardDes = function(url) {
    $mdDialog.show({
      controller: DialogController,
      templateUrl: url,
    });
  };

I remember when I did it before it involved something with setting up a ng-model, but I seriously cannot find the documentation either online or in my hard drive. >.<

I forgot to mention I also tried this:

<md-card ng-repeat="card in cards" class="noselect hietim {{card.size}}" data-link="{{card.link}}" ng-click="showCardDes($event)" md-ink-ripple>

And in my Angular Script I used:

  $scope.showCardDes = function(event) {
    var tempUrl = $(event.target).attr('data-link');
    $mdDialog.show({
      controller: DialogController,
      templateUrl: tempUrl,
    });
  };

This will return:

Uncaught TypeError: Cannot read property 'hasAttribute' of undefined

If you pass in ng-click="showCardDes($event)" you can access the element within the $event object.

So in your javascript it would look like this:

  $scope.showCardDes = function($event) { var btn = $event.currentTarget; var tempUrl = $(btn).attr('data-link'); $mdDialog.show({ controller: DialogController, templateUrl: tempUrl, }); }; 

as others said you can use $event for this but in your case it is not the angular way of doing it. You should pass your model as parameter and read its property;

<md-card ng-repeat="card in cards" ng-click="showCardDes(card)">

and in your controller;

$scope.showCardDes = function(card) {
  var tempUrl = card.link;
  $mdDialog.show({
    controller: DialogController,
    templateUrl: tempUrl,
  });
};

The ngClick directive passes a named $event property to your handler, which you can use to access "this" (aka the event target).

<md-card ng-click="showCardDes($event)" ...>

Then your controller may look like this:

$scope.showCardDes = function(event) {
  var tempUrl = $(event.target).attr('data-link');
  $mdDialog.show({
    controller: DialogController,
    templateUrl: tempUrl,
  });
};

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