角度间隔只运行一次

时间:2017-07-22 11:34:25

标签: javascript angularjs

我正在学习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上完美运行。 看起来我的帖子主要是代码所以我正在写这行。

1 个答案:

答案 0 :(得分:3)

你搞砸了$timeout&amp;的依赖用法。 $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