Rakesh
Rakesh

Reputation: 63

this keyword in angular js shows Type Error

I want to target and element which is clicked in angular but without jQuery.

$scope.hide = function() {
    this.querySelector('ul').style.display = 'none'
};

But I am getting this error:

TypeError: this.querySelector is not a function.

I am new to Angular. Am I doing anything wrong?

Upvotes: 0

Views: 453

Answers (3)

Piyush.kapoor
Piyush.kapoor

Reputation: 6803

$scope.hide = function() {
    document.querySelector('ul').style.display = 'none'
};

Upvotes: 0

Jeroen
Jeroen

Reputation: 63780

The this inside that function will not refer to the object you think it refers to (try debugging and/or logging it). I suggest reading up on how the this keyword works in Javascript.

Instead, you're looking to do just document.querySelector.

At any rate, the "Angular way" to show/hide things is using a directive like ngShow. E.g.:

$scope.isVisible = true;
$scope.hide = function() { $scope.isVisible = false; };
<div ng-show="isVisible">...</div>

Upvotes: 1

line-segment
line-segment

Reputation: 389

The this keyword is a reference to an object. Here you don't have an object so no point of referencing it. That's why it says query selector is not a function cause your this isn't defined. Change this with document.

Upvotes: 1

Related Questions