gpt4 book ai didi

javascript - Angular 间隔仅运行一次

转载 作者:行者123 更新时间:2023-12-01 03:20:25 25 4
gpt4 key购买 nike

我正在学习 AngularJS,我的简单间隔函数仅触发一次。这与 W3 学校的例子相同。代码如下:

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Angular Project</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<div class="container">
<div id="app" ng-app="myApp" ng-controller="myCtrl">
<input type="text" ng-model="person.firstName">
<input type="text" ng-model="person.surName">
<p>{{person.firstName + " " + person.surName | uppercase}}</p>
<button ng-click="orderBy('name')">name</button>
<button ng-click="orderBy('surname')">surname</button>
<button ng-click="orderBy('id')">id</button>
<ul>
<li ng-repeat="x in list | orderBy: myOrder">{{x.name + " " + x.surname + " ID:" + x.id}}</li>
</ul>
<p>{{pair()}}</p>
<input type="text" ng-model="test">
<p ng-repeat="x in guests | filter: test">{{x}}</p>
<br>
<p>Page URL: {{myUrl}}</p>
<p>Welcome Server Message: {{myWelcome}}</p>
<p>Timing function: {{myHeader}}</p>
<p>Time: {{theTime}}</p>
</div>
</div>
<script src="main.js"></script>
</body>
</html>

还有 JS:

angular.module('myApp', []).controller('myCtrl', ['$scope', '$location', '$http', '$timeout', '$interval', function($scope, $location, $http, $interval, $timeout){
$scope.person = {
firstName: '', surName: ''
};
$scope.list = [
{name: 'John', surname: 'Doe', id: 1},
{name: 'Daisy', surname: 'Duck', id: 2},
{name: 'Ben', surname: 'Hilfiger', id: 3}
];
$scope.orderBy = function (arg) {
$scope.myOrder = arg;
};
$scope.pair = function (arg) {
return $scope.list[1].name;
};
$scope.guests = ['Jane Doe', 'John Doe', 'Benny Thug', 'Bill Gates'];
// location object
$scope.myUrl = $location.absUrl();
// console.log($location);
// http obejct
$http.get("welcome.txt").then(function (response) {
$scope.myWelcome = response.data;
// console.log(response);
});
$timeout(function () {
$scope.myHeader = "Timeout Function running OK!";
}, 2000);
$interval(function () {
$scope.theTime = new Date().toLocaleTimeString();
}, 1000);
}]);

它应该按原样工作,但是,它在 W3 上工作得很好。看起来我的帖子主要是代码,所以我写了这一行。

最佳答案

您搞乱了 Controller 工厂函数内 $timeout$interval 的依赖项使用,这就是您的 $interval 实例被处理的原因作为 $timeout 并且它被解雇了一次

.controller('myCtrl', ['$scope', '$location', '$http', '$timeout', '$interval', 
function($scope, $location, $http, $interval, $timeout) {

应该是

.controller('myCtrl', ['$scope', '$location', '$http', '$timeout', '$interval', 
function($scope, $location, $http, $timeout, $interval) {

Demo Plunker

关于javascript - Angular 间隔仅运行一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45254060/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com