在angularjs中自动选择第一个ng-repeat元素?

时间:2014-02-13 16:11:15

标签: javascript angularjs

关于如何做到这一点的任何想法?

我基本上有1个控制器设置,如果你点击一个元素,上面会出现一个动画,但是,一旦页面加载就应该激活/点击第一个元素...... < / p>

一些代码:

动画在此处显示:

<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>

动画选择:

<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>

这是我的控制器:

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;
        };
    });

2 个答案:

答案 0 :(得分:1)

在您的控制器中,列表加载后,调用第一个索引上的showAnimation

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

答案 1 :(得分:0)

由于:

[] == false 

所以,你可以这样做if

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

如果主题是一个空数组,那么事情就不会发生。

如果主题是一个数组至少有一个主题,将触发showAnimation函数