Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the $this in angularjs

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.

like image 883
Bhumi Singhal Avatar asked Apr 23 '13 07:04

Bhumi Singhal


People also ask

What is$ q in AngularJS?

$q is integrated with the $rootScope. Scope Scope model observation mechanism in AngularJS, which means faster propagation of resolution or rejection into your models and avoiding unnecessary browser repaints, which would result in flickering UI. Q has many more features than $q, but that comes at a cost of bytes.

How to set HTTP request header in AngularJS?

To add headers for an HTTP method other than POST or PUT, simply add a new object with the lowercased HTTP method name as the key, e.g. $httpProvider. defaults. headers. get = { 'My-Header' : 'value' } .

How to use promise in AngularJS?

Example of a Promise // We create our promise $http. get('api/status') // that once complete will call either our success callback function // or our error callback function . then(function success(response) { // handle our response object $log. log(response); }, function error(response) { // handle our error $log.


2 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

like image 138
Arun P Johny Avatar answered Oct 13 '22 23:10

Arun P Johny


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

like image 31
NilsH Avatar answered Oct 14 '22 00:10

NilsH