2015-02-17 98 views
0

Angular全新,我可以想出100種不同的方式來完成Angular之外的這些功能,但是推動自己學習Angular方法。我的目標是,我有一個內含純文本的元素。我想每隔x秒旋轉一次文字。這裏的基本HTML:如何在Angular中旋轉文本值?

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

跨度是我希望文本從旋轉樂趣「吸」,「真棒」,「硬」,「易」每隔x秒數。一個不錯的轉換也將包含在內,但是尋找使用Angular實現功能的最佳方式。我一直在尋找創建一個指令,並使用Angular的間隔,但沒有得到它。

如果所有可能的值都可以包含在HTML中,那將是非常好的,但我願意提供最佳方式的建議。

+0

你試過了'NG-style'指令? – 2015-02-17 20:16:18

+0

我不想對類做任何事情。我正在嘗試交換文本。 – 2015-02-17 20:22:46

回答

2

入住這普拉克我做:

rotating text in angularjs

讓我們定義一個字的數組:

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

該指令

<span rotate-text></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 

由於$間隔只有開始工作指定的延遲之後,我們需要將$區間之外顯示數組的第一個字,就像這樣:

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

因此,有必要開始索引在1 $間隔功能,不爲0,通過使用(i + 1),而不是(i)中,像這樣:

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

完美,謝謝! – 2015-02-18 00:16:25

0

在操縱角文本是相當直接的;完成此操作的最佳方法是使用'ngModel'的控制器,我們通常稱其爲'ngModelCtrl'。通過創建一個自定義指令並告訴它需要一個'ngModel'指令,您可以訪問這個特殊控制器,該控制器爲您提供了一個API來操縱'ngModel'的文本值。

這裏的Plunker:http://plnkr.co/edit/I2HvpHn5AnnCCe8rtQOW

的index.html

<body ng-app  = "YourAppName" 
     ng-controller = "YourAppCtrl"> 
    <h1>Hello Plunker!</h1> 
    <h2>Rotating text in Angular is <span ng-model = "currentAdjective" rotate-text > {{ currentAdjective }} </span></h2> 
    </body> 

的script.js

angular.module('YourAppName', []); 

angular.module('YourAppName') 
     .controller('YourAppCtrl', function($scope) { 
     $scope.currentAdjective; 
     }) 
; 


angular.module('YourAppName') 
     .directive('rotateText', function($interval) { 
      return { 
       require: 'ngModel', 
       link: function($scope, $elem, $attrs, ngModelCtrl) { 
        var adjectivesToRotate = ["sucks", "hard", "awesome", "easy"]; 
        var lengthOfAdjectives = adjectivesToRotate.length; 
        var randomIndex  = Math.floor(Math.random() * (lengthOfAdjectives)); 

        var beginInterval = $interval(function() {     
        ngModelCtrl.$setViewValue(adjectivesToRotate[randomIndex]); 
        randomIndex = Math.floor(Math.random() * (lengthOfAdjectives)); 
        }, 1000); 
      } 
     }; 

    }) 
; 
+0

看起來不錯,但是有沒有辦法在HTML中保留默認文本(不會被JS取代)? – 2015-02-18 00:07:32

+0

這將涉及利用'$ elem'對象,我不推薦它,因爲它只是一個jQuery包裝的DOM的輕量級版本。我以爲你想要這個角度的方法,所以我給你一個你在利用'ngModel'。 – howardlykim 2015-02-18 00:50:46