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

查看:28
本文介绍了如何在 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.

推荐答案

检查我所做的这个 plunk:

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天全站免登陆