AngularJS - 在ng-repeat中使用indexOf来显示/隐藏值

时间:2014-10-15 09:50:20

标签: angularjs angularjs-scope angularjs-ng-repeat ng-show ng-hide

我有一个包含大量数据的JSON文件:

myData.JSON:

{
"Addresses": {
    "AddressList": [
        {
            "HouseNumber": 201,
            "Street": "Victoria Lane",
            "Postcode": "SW1 8ES"
        },
        {
            "HouseNumber": 10,
            "Street": "Allen Close",
            "Postcode": "NG2 3TD"
        },
        {
            "HouseNumber": 57,
            "Street": "Thomas Street",
            "Postcode": "DR12 6TE"
        },
        {
            "HouseNumber": 57,
            "Street": "Old Lister Street",
            "Postcode": "OL4 5TH"
        },
        {
            "HouseNumber": 45,
            "Street": "Milk Round Street",
            "Postcode": "MK6 4HG"
        },
        {
            "HouseNumber": 102,
            "Street": "Jersey Quarter Avenue",
            "Postcode": "DR12 6TE"
        },
        {
            "HouseNumber": 845,
            "Street": "MR HAPPY STREET",
            "Postcode": "MR3 0FJ"
        }
    ]
}

我试图通过indexOf找到来自Street的返回值匹配的div

HTML:

<div ng-repeat="address in Addresses.AddressList">
    {{ address.HouseNumber }}, {{ address.Street}}, {{ address.Postcode }}
    <div ng-show="address.Street.toLowerCase().indexOf('MR HAPPY STREET') == 0">
        MR HAPPY STREET WAS FOUND
    </div>
    <div ng-show="address.Street.toLowerCase().indexOf('Milk Round Street') == 0">
        Milk Round Street WAS FOUND
    </div>
</div>

这似乎不起作用。您可以通过indexOf执行此类ng-show吗?

3 个答案:

答案 0 :(得分:6)

您的问题是您比较了两个不相同的字符串:使用toLowerCase()函数后,您的字符串Milk Round Street看起来像milk round street。因此indexOf()将返回-1。 这就是为什么你需要以小写字母比较2个字符串的原因,例如:

<div ng-show="address.Street.toLowerCase().indexOf('mr happy street') == 0">

或:

<div ng-show="address.Street.toLowerCase().indexOf(('MR HAPPY STREET').toLowerCase()) == 0">

答案 1 :(得分:1)

使用此

<div ng-repeat="address in Addresses.AddressList">
    {{ address.HouseNumber }}, {{ address.Street}}, {{ address.Postcode }}
    <div ng-show="showByJs(address,'MR HAPPY STREET')">
        MR HAPPY STREET WAS FOUND
    </div>
    <div ng-show="showByJs(address,'Milk Round Street')">
        Milk Round Street WAS FOUND
    </div>
</div>

在控制器写入

    $scope.showByJs=function(address, indexofWord){
    if (address.Street.toLowerCase().indexOf(indexofWord) == 0)
    {
       return true;
    }else
     {
       return false
}
    }

答案 2 :(得分:1)

您需要检查"MR HAPPY STREET""Milk Round Street"的小写字母,因为您尝试与address.Street的小写字母进行比较。

<div ng-repeat="address in Addresses.AddressList">
    {{ address.HouseNumber }}, {{ address.Street}}, {{ address.Postcode }}
    <div ng-show="address.Street.toLowerCase().indexOf(('MR HAPPY STREET').toLowerCase()) == 0">
        MR HAPPY STREET WAS FOUND
    </div>
    <div ng-show="address.Street.toLowerCase().indexOf(('Milk Round Street').toLowerCase()) == 0">
        Milk Round Street WAS FOUND
    </div>
</div>