2017-07-22 56 views
0

我正在學習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。 它看起來像我的文章主要是代碼,所以我正在寫這一行。

+0

你可以創建ap lunker或這裏的代碼片段?所以我們可以檢查出現了什麼問題 –

+0

JSFiddle似乎不能使用此代碼... https://jsfiddle.net/k8bf3r44/ –

回答

3

您與$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

+0

非常感謝!很高興知道這樣的事情! –