redrom
redrom

Reputation: 11632

AngularJS Scope Apply does not working on click

I'm trying to se scope variable value after on click event using the following code:

$('#teamDetailTabs a').click(function(data) {
                $scope.$apply(function(){
                    console.log($(this).attr('data-target'));
                    $scope.activeTab = $(this).attr('data-target');
                    console.log($scope.activeTab);
                });
});

Problem is that value $scope.activeTab is undefined even if I used $scope.apply.

How can I solve it please?

Thanks for any advice.

Upvotes: 2

Views: 151

Answers (1)

dfsq
dfsq

Reputation: 193261

The context (this) inside apply call is not what you expect, it's no longer a DOMElement. So you can fix it like this:

var self = this;
$scope.$apply(function() {
    console.log($(self).attr('data-target'));
    $scope.activeTab = $(self).attr('data-target');
    console.log($scope.activeTab);
});

However, I strongly encourage you to go with ngClick and never use jQuery style approach in Angular app. Take a look at this very detailed thread.

Upvotes: 4

Related Questions