Javascript AngularJS 中的字符串比较
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30995343/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
String comparison in AngularJS
提问by Anusha
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...
我正在尝试比较 AngularJS 中的两个字符串,并且我在网上看过示例。据我了解,您可以使用 angular.equals(str1, str2),您可以使用 ===,如果您确定两者都是字符串,则可以使用 ==...
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?
当我运行代码时,调用 inc1() 函数。第一个警报出现“inc1 called”。但是第二个警报“Inside for loop”只执行一次。它应该执行两次,不是吗?
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.
并且 if(condition) 内部的警报根本不执行。如果我删除“if”块,则警报“Inside for loop”会运行两次。
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.
如果有人能告诉我我在这里做错了什么,我将非常感激。我使用过 angular.equals()、=== 和 ==,但每次都会发生同样的事情。
This is how the HTML and AngularJS codes go:
这是 HTML 和 AngularJS 代码的运行方式:
HTML:
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:
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'
//说,名字是'Dolphin'
回答by Beri
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");
}
}
回答by 404
You should be comparing with the $rootScope.items[i].name instead of $rootScope.items.names[i]
您应该与 $rootScope.items[i].name 而不是 $rootScope.items.names[i] 进行比较
回答by borja gómez
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)".
问题是 name 始终未定义 $scope.name 未定义。在视图中,而不是 ng-click="inc1(name)" 放置 ng-click="inc1(x.name)"。

