ac360
ac360

Reputation: 7835

Angular – Simple Typewriter Effect?

There is a beautiful typewriter directive already written, but I'm looking for something more simple, that just adds each letter after an interval. I can't get this to work. It shows the text all at once. Something is wrong with the $timeout. Does anyone have any suggestions?

var time = 1000;
var addLetter = function(i) {
    $scope.string2 = $scope.string.substr(0, i);
};
for (var i = 0, len = $scope.string.length; i < len; i++) {
    (function(time) {
        $timeout(function() {
            addLetter(i);
        }, (time + 300));
    })(i);
}

Upvotes: 0

Views: 2164

Answers (2)

ac360
ac360

Reputation: 7835

Update - This is working for me, not sure if it could be more efficient...

var time = 0;
var addLetter = function(i) {
    $scope.string2 = $scope.string.substr(0, i);
};
for (var i = 0, len = $scope.string.length; i < len + 1; i++) {
    time = time + 50;
    (function(time, i) {
        $timeout(function() {
            addLetter(i);
        }, (time));
    })(time, i);
}

Upvotes: 0

lucuma
lucuma

Reputation: 18339

Here is an alternate way.

var content = "contentcontentcontentcontentcontentcontentcontentcontentcontentcontentcontent";

$scope.type = "";
var i=0;

var timer = $interval(function(){
    if(i<content.length)
        $scope.type += content[i];
      else
        $interval.cancel(timer);

     i++; 
     $scope.$apply();
}, 100); 

Credit: https://gist.github.com/frozonfreak/8018689

Demo: http://plnkr.co/edit/BILaWVuNpao2zcIInXLl?p=preview

Upvotes: 3

Related Questions