如何在设定的时间间隔内为ng-model注入html更新?

时间:2017-08-14 08:33:55

标签: javascript html angularjs setinterval angularjs-ng-model

我正在尝试创建一个页面,其中包含每0.5秒更新一次的文本字符串。我尝试了下面的代码,但是当我进入页面时,它只会在我输入时加载文本,但不会更新并相应地更改时间。关于如何使其发挥作用的任何建议?

//how fast each update should occur
var fRate = 500;
//how much time has past
var timeElapsed = 0;

function fRotate() {
  //some codes that does a clock
	timeElapsed += fRate;
	setTimeout(fRotate, fRate);
}

function startRotate() {
	timeElapsed = 0;
	fRotate();
}

var t = 0;
// create the module and name it myApp
	var app = angular.module('myApp', ['ngSanitize']);


//dynamiclly update angularjs to read ng-bind-html elements
	app.directive('dynamic', function($compile) {
			return {
				restrict: 'A',
				replace: true,
				link: function (scope, element, attrs) {
					scope.$watch(attrs.dynamic, function(html) {
						element[0].innerHTML = html;
						$compile(element.contents())(scope);
					});
				}
			};
	});
	

//Controller, injects the string into html
	app.controller('forestController', function($scope, $sce) {
		$scope.header = 'The Woodland';
        $scope.desc = 'An uninhabited land';
		$scope.forest = setInterval(forestContent(timeElapsed),500);
	});

//array of strings to be injected
var forestContent = function (t) {
		if (0 <= t && t < 10){
			return 'You can see ...';
		}
		else if (10 <= t && t < 15){
			return 'cometh f’rth...';
		}
//etc., the rest of the array skipped on this post		
   else {
			return '';
		}
	}
<html>
<head>
<!-- angularjs scripts -->
	<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.11/angular.min.js"></script>
 	<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.11/angular-sanitize.js"></script>
</head>
<body ng-controller="forestController">
<div id = "content">
    <h1>here are some content:</h1>\
<!-- dynamic defined in js script with app.directive -->
    <p dynamic="forest"></p>
</div>
</body>

0 个答案:

没有答案