1252748
1252748

Reputation: 15389

$scope.$watch function not firing on nodelist.length change as expected

I would like to do something when a <li> element is hovered over. I thought that I could do it like this

$scope.$watch(function(){
    return  document.querySelectorAll("li:hover").length;
},
function(newVal, oldVal){
    console.log(newVal, oldVal);
});

based on a solution I found here. When the application loads, I see 0 0 in the console, which is what I'd expect. However when I hover over a <li> element, I expect to see 0 1. But I don't see anything. I think that selector is good because entering

setInterval(function(){
   console.log( document.querySelectorAll("li:hover").length )
}, 500);

into the console will print 0 every half second until I hover over a <li> at which point, I'll see 1. How can I change my $scope.$watch to watch the length of this nodelist?

Upvotes: 1

Views: 56

Answers (1)

Sudharsan S
Sudharsan S

Reputation: 15403

In my learning Experience,

$scope.$watch only watch the scope objects and scope providers. It does not watch the Jquery with dom manipulation. One think you do it assign the jquery object it in the scope and watch the change may you can proceed the next level.

$scope.liLength = document.querySelectorAll("li:hover").length;

$scope.$watch(function($scope){
    return  $scope.liLength;
},
function(newVal, oldVal){
    console.log(newVal, oldVal);
});

Upvotes: 2

Related Questions