String comparison in AngularJS

48k Views Asked by At

I'm trying to compare two strings in AngularJS, and I've seen examples online. As I understand it, you can use angular.equals(str1, str2), you can use ===, you can use == if you're sure that both are strings...

I've tried all three, but I don't get the result. Something must be wrong in what I've done, but I don't know what it is.

When I run the code, the inc1() function is called. The first alert appears "inc1 called". But the second alert, "Inside for loop", executes only once. It should execute twice, shouldn't it?

And the alert inside of the if(condition) does not execute at all. If I remove the 'if' block, then the alert "Inside for loop" runs two times.

I'd be much obliged if someone could tell me what I'm doing wrong here. I've used angular.equals(), === and ==, but the same thing happens everytime.

This is how the HTML and AngularJS codes go:

HTML:

<a class="tab-item" ng-repeat = "x in items" ng-if="name==x.names" ng-click="inc1(name)">
  <i class="icon ion-thumbsup"></i>
  Like
 </a> 

AngularJS:

$rootScope.items = [
{ id: 1, names: 'Dolphin', image: 'dolphin.jpg'}, { id: 2, names: 'Donkey', image: 'donkey.jpg'}];

$scope.inc1 = function(name) {

alert("inc1 called");
for(var i=0;i<$rootScope.items.length;i++)
{
    alert("Inside for loop");
    if (name === $rootScope.items.names[i])
        {
        alert("If condition satisfied");
        }
}
}

//Say, name is 'Dolphin'

3

There are 3 best solutions below

2
On BEST ANSWER

You are iterating over wrong node:)

for(var i=0;i<$rootScope.items.length;i++)
{
    alert("Inside for loop");
    if (name === $rootScope.items[i].names) // you iterate over items, not names, which it an Json property inside item
        {
        alert("If condition satisfied");
        }
}
1
On

You should be comparing with the $rootScope.items[i].name instead of $rootScope.items.names[i]

0
On

The problem is that name is allways undefined $scope.name is not defined. In the view instead of ng-click="inc1(name)" put ng-click="inc1(x.name)".