jamesbar
jamesbar

Reputation: 147

auto select first ng-repeat element in angularjs?

any idea on how to do this?

i basically have 1 controller set up and if you click on an element, an animation appears above, however, the first element should be active/clicked as soon as the page loads...

some code:

Animation Appears here:

<div class="animation">
    <div ng-repeat="theme in themes" ng-show="isActive($index);" ng-if="isActive($index);">
        <img id="id_{{ theme.animation_id }}" ng-src="{{ theme.animation_gif_url }}" class="active" />
    </div>
</div>

Animation selection here:

<div class="theme-select animated fadeInUp">
    <div class="theme-container" ng-repeat="theme in themes" ng-click="showAnimation($index);">
        <div id="theme_{{ theme.animation_id }}" class="theme">
            <img ng-src="{{ theme.icon_url }}" />
            <div class="name">
                {{ theme.name }}
            </div>
        </div>
    </div>
</div>

Here's my controller:

themeFunction(function(themeData) {
        name = [];
        themeID = [];
        animationURL = [];
        var themes = $scope.themes = themeData.themes;
        for (var t = 0; t < themes.length; t++) {
            animationURL = themes[t].animation_url;
            themeID = themes[t].animation_id;
            iconURL = themes[t].icon_url;
            name = themes[t].name;
            animationGifUrl = themes[t].animation_gif_url;
            $scope.themeID = themeID;
            if ($scope.themes[t].animation_gif_url == 'NULL' || $scope.themes[t].animation_gif_url == null || $scope.themes[t].animation_gif_url == '.gif') {
                // console.log(name + " are null or weird");
                $scope.themes[t].animation_gif_url = iconURL;
            } else {
                $scope.themes[t].animation_gif_url = animationGifUrl;
            }
        }
        $scope._Index = 0;
        $scope.isActive = function(index) {
            return $scope._Index === index;
        };
        $scope.showAnimation = function(index) {
            selectedTheme = $(this).attr('theme');
            console.log('Selected ' + selectedTheme.animation_id);
            $scope._Index = index;
        };
    });

Upvotes: 0

Views: 1039

Answers (2)

Chen-Tsu Lin
Chen-Tsu Lin

Reputation: 23234

Because:

[] == false 

So, you can do if simply like this:

if (themes) $scope.showAnimation(0);

If themes is a empty array, not thing will happened.

If themes is a array has at least one theme, will trigger showAnimation function

Upvotes: 0

tymeJV
tymeJV

Reputation: 104775

In your controller, after your list loads up, call the showAnimation on the first index

...list loads up
$scope.themes = data;
if (data.length) $scope.showAnimation(0);

Upvotes: 1

Related Questions