如何在数组中存在具有特定值的键时使用ng-show

How to use ng-show when a key with a certain value exists in an array?

本文关键字:ng-show 数组 存在      更新时间:2023-09-26

假设我有以下数组:

(这是编造的,因为我为一个客户工作,他的数据我不能在这里发布)

collections: {
    browsers: [
        {
            label: 'Chrome',
            visitors: 50,
            bounces: 23
        },
        {
            label: 'FireFox',
            visitors: 30,
            bounces: 15
        },
        {
            label: 'Internet Explorer',
            visitors: 60,
            bounces: 33
        },
        {
            label: 'Opera',
            visitors: 4,
            bounces: 2
        },
    ]
}

如果我想在我的模板中显示Chrome的数据,目前它是可用的,我通常会使用这样的东西:

<div ng-show="collections.browser.chrome">content</div>

但是因为它是一个数组,所以这不起作用


是否有一种方法来使用ng-show与当前对象?

你可以这样做:

<div ng-repeat="browser in collections.browsers">
  <div ng-show="browser.label == currentBrowser">content</div>
</div>

这个HTML将基于控制器上的这些值

$scope.collections = //Your JSON Here
$scope.currentBrowser = 'chrome'; //Or whatever you want

你可以这样做

控制器

$scope.hasBrowser = function(name) {
    return collections.browsers.some(function(browser) {
        return browser.label === name;
    });
};
html

<div ng-show="hasBrowser('Chrome')">content</div>

=)