如何在Angular中旋转文本值? [英] How do you rotate text values in Angular?

查看:86
本文介绍了如何在Angular中旋转文本值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于Angular来说是完全陌生的,我可以想到100种不同的方法来在Angular之外实现这一目标,但会促使我学习Angular的方法.我的目标是,我的元素中包含纯文本.我想每x秒旋转一次该文本.这是基本的HTML:

Completely new to Angular and I can think of 100 different ways to accomplish this outside of Angular, but pushing myself to learn the Angular ways. My goal, I have an element that has plain text in it. I want to rotate that text every x seconds. Here's the base HTML:

<h2>Rotating text in Angular is <span>fun</span></h2>

跨度是我希望文本每x秒钟就从有趣变成糟透了",令人敬畏",艰苦",轻​​松"的地方.一个不错的过渡也将包括在内,但正在寻找使用Angular实现功能的最佳方法.我一直在研究创建指令并使用Angular的间隔,但并没有完全理解它.

The span is where I want the text to rotate from fun to 'sucks', 'awesome', 'hard', 'easy' every x number of seconds. A nice transition will also be included, but looking for the best way to implement the functionality using Angular. I've been looking into creating a directive and using Angular's interval, but not quite getting it.

如果所有可能的值都可以包含在HTML中,那就太好了,但是我愿意提出建议,以寻求最佳方法.

It would be great if all the possible values could be included in the HTML, but I'm open to suggestions for the best way to do this.

推荐答案

检查我做的这个小东西:

Check this plunk I made:

在angularjs中旋转文本

让我们定义一个单词数组:

Let's define a word array:

scope.wordArr=['fun','sucks', 'awesome', 'hard', 'easy'];

指令

<span rotate-text></span>

在跨度内每秒钟旋转一次数组中的单词.

rotates the words from the array every sec inside the span.

function updateWord(i) {
    var j = (i + 1) % (scope.wordArr.length); // (i + 1) to start at second word
    //so the j rotates like: 1, 2, 3, 4, 0, 1, 2,...
    element.text(scope.wordArr[j]); //changes text inside span
}

element.text(scope.wordArr[0]); // displays "fun"
stopWord = $interval(updateWord, 1000); //executes 'updateWord' every second

由于$ interval仅在指定的延迟后开始工作,因此我们需要在$ interval外显示数组的第一个字,如下所示:

As the $interval only starts working after the delay specified, we need to display the 1st word of the array outside the $interval, like so:

element.text(scope.wordArr[0]); //displays "fun"

因此需要通过使用(i + 1)而不是(i)在$ interval函数中将索引从1开始而不是0,如下所示:

Hence the need to start indexes in the $interval function at 1, not 0, by using (i + 1) instead of (i), like so:

var j = (i + 1) % (scope.wordArr.length);

这篇关于如何在Angular中旋转文本值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆