5

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'

1

3 Answers 3

6

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");
        }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Ahaa!!! So is that how you do it? Now it makes sense! :D I thought you had to do items.names[i]!! Thanks!! Now it works!! ;)
If ot works for you you can close this issue then:) To keep all closed tasks clean. Be glad to help:)
2

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

1 Comment

Yeah, thanks! I should have realised what i did wasn't making sense :D
0

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)".

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.