Jeffrey Roosendaal
Jeffrey Roosendaal

Reputation: 7157

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

Let's say I have the following array:

(it's made up, since I work for a customer who's data I can't post here)

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
        },
    ]
}

If I would like to show data for Chrome in my template, at the moment it'll be avaliable, I would normally use something like:

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

But since it's an array, this won't work.


Is there a way to use ng-show with the current object?

Upvotes: 0

Views: 1158

Answers (2)

nerv
nerv

Reputation: 21

You can do something like this

controller

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

html

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

=)

Upvotes: 2

Pierre-Alexandre Moller
Pierre-Alexandre Moller

Reputation: 2354

You can do something like this :

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

And this HTML will be base on these values on your controller :

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

Upvotes: 2

Related Questions