Home » Angularjs » Get the $this in angularjs

Get the $this in angularjs

Posted by: admin November 30, 2017 Leave a comment

Questions:

Here is my issue.

HTML structure :

<tr><td><a ng-click=aClick()>Click Me</a></td></tr>

I cannot have any id/class associated with the and

What I require is that on the click of ‘Click Me’, the <tr> gets hidden. I need a jQuery solution. Some how I am not able to use $(this).

FUNCTION:

$scope.aClick = function() {
   $(this).parent().parent().css('display','block');
};

But this statement gives me an error.

Answers:

Note: I wouldn’t recommend using dom manipulation in a controller, you can write a directive to do this. That said you can use the $event to get the event object, from which you can get the event target and use it with jquery.

<tr><td><a ng-click="aClick($event)">Click Me</a></td></tr>

And

  $scope.aClick = function(event) {
     $(event.target).parent().parent().css('display','none');
  };

Demo: Plunker

Update
A more appropriate angular solution will be is to use ng-hide

<tr ng-hide="hideRow"><td><a ng-click="hideRow = true">Click Me</a></td></tr>

Demo: Plunker

Updated demo with ng-repeat

Questions:
Answers:

Since you’re using angular, you should very seldom need to do actual dom manipulation. Instead, check out the ng-hide/ng-show directive that should do this for you.

An example from the Angular docs:

<body>
    Click me: <input type="checkbox" ng-model="checked"><br/>
    Show: <span ng-show="checked">I show up when you checkbox is checked?</span> <br/>
    Hide: <span ng-hide="checked">I hide when you checkbox is checked?</span>
</body>

Edit

If the variable in the expression is updated asynchronously, you can force an updated with $scope.$apply

Questions:
Answers:

You can use this:

JavaScript

function TestCtrl($scope) {
    $scope.clickMe = function ($event) {
        $($event.target).parent().parent().css('display','none');
    };
}

HTML

<div ng-app>
    <div ng-controller="TestCtrl">
        <a ng-click="clickMe($event)">Click me</a>
    </div>
</div>

Live demo

Questions:
Answers:

why don’t you do something simple like this?
I assume you run this in loop…

<div ng-repeat="row in table">
<tr>
    <td>
        <a ng-class="{'hideme': hiddenRows[row.id]}" ng-click="hiddenRows[row.id] = true">Click Me</a>
    </td>
</tr>
</div>

or even better

<div ng-repeat="row in table">
    <tr ng-show="!hiddenRows[row.id]">
        <td>
            <a ng-click="hiddenRows[row.id] = true">Click Me</a>
        </td>
    </tr>
</div>

(I didn’t test it but it should give you idea)