使用$ interval和get请求

时间:2016-02-09 15:12:38

标签: angularjs

我尝试使用$ interval创建新的get请求。 get请求的结果将每秒更新模型。但是没有调用间隔:

https://plnkr.co/edit/SudMFW8vSCCflyN0eJGl?p=preview

间隔是在一个指令中定义的,也许这是对带指令的间隔的错误使用?

下面的src:

2. http-hello2.html

<!doctype html>
<html ng-app="app">
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
    <script src="script.js"></script>
  </head> 
  <body>

  <div ng-controller="FetchCtrl">

<label>Filter: <input ng-model="search"></label> 

  <status-viewer ng-repeat="sourceUrl in sourceUrls | filter:search track by $index " url="sourceUrl"></status-viewer>
</div>


  </body>
</html>

<!--<h1>{{url}}</h1>-->
<div>
    <p>{{model}}</p>
</div>

var myapp = angular.module('app', []).controller('FetchCtrl', FetchCtrl)

myapp.directive('statusViewer', function ($http , $interval) {
            return { 
                restrict: 'E',
                templateUrl: 'mytemplate.html', 
                scope: {
                    url: '='
                },  
                link: function (scope, elem, attrs, ctrl) {

                    console.log('invoked')

                    var refreshData = function() {
                    $http.get(scope.url).success(function (data) {
                        scope.model = JSON.stringify(data);
                    });
                 };

                    var promise = $interval(refreshData, 1000);

                    // Cancel interval on page changes
                    scope.$on('$destroy', function(){
                    if (angular.isDefined(promise)) {
                      $interval.cancel(promise);
                      promise = undefined;
                     }
                   });

                    $http.get(scope.url).success(function (data) {
                        scope.model = JSON.stringify(data);
                    });
                }
            };
        });

function FetchCtrl($scope, $http, $q , $parse) {


$scope.sourceUrls = [
                'http-hello2.html'
            ,'http-hello2.html'];



} 

更新

使用间隔&amp;以这种方式更新模型的指令是否正确?

1 个答案:

答案 0 :(得分:-1)

使用scope.$watch$interval更理想的方式是根据范围变量的更改触发函数,因为只有在对变量进行实际更改时才会执行代码。像这样的东西会起作用:

scope.$watch('url', function(newValue, oldValue) {
  if (newValue !== oldValue) {
    $http.get(...).success(function(data) {
      scope.model = data;
    });
  }
}