问题描述
我有这方面的工作实现房颤angularJS应用程序,它获取从URL一些链接和油漆他们。
然而在URL链接正在不断更新,我想更新periodcially这个$ scope.listlinks,让说每10秒。
我试着玩的setInterval没有运气。
的JavaScript
VAR应用= angular.module('应用',[]);
App.controller('ListLinksCtrl',
函数的get($范围,$ HTTP){
$ http.get('http://example_url.com/my_changing_links_json')。然后(
功能(RES){$ scope.listlinks = res.data;});
}
);
HTML
< DIV ID =CNT1NG控制器=ListLinksCtrl>
< DIV NG重复=singlelink在listlinks>
&所述; A HREF ={{singlelink.url}}>
{{singlelink.destination}}
&所述; / A>
< / DIV>
< / DIV>
虽然jvandemo的回答会的工作,我认为它可以稍微得到改善。通过使用的setInterval
,它打破了角以下,使控制困难的单元测试的依赖注入约定。
角目前不支持的setInterval
通过其内置的服务,但你可以使用 $超时
服务,以产生相同的功能。我控制器改成这样:
app.controller('MainCtrl',函数($范围,$ HTTP,$超时){ //函数来获取数据
$ scope.getData =功能(){
$ http.get('style.css文件')
.success(功能(数据,状态,头,配置){ //你的code在这里
的console.log('获取的数据!);
});
}; //函数使用的setInterval $超时服务复制。
$ scope.intervalFunction =功能(){
$超时(函数(){
$ scope.getData();
$ scope.intervalFunction();
},1000)
}; //揭开序幕间隔
$ scope.intervalFunction();});
I have this working implementation af a angularJS app which fetches some links from an URL and paint them.However the links on the URL are being updated constantly, I would like to update periodcially this $scope.listlinks, let say every 10 seconds.
I tried playing with setInterval with no luck.
Javascript
var App = angular.module('App', []);
App.controller('ListLinksCtrl',
function get($scope, $http ) {
$http.get('http://example_url.com/my_changing_links_json').then(
function(res){$scope.listlinks = res.data;});
}
);
HTML
<div id="cnt1" ng-controller="ListLinksCtrl">
<div ng-repeat="singlelink in listlinks">
<a href="{{ singlelink.url }}">
{{ singlelink.destination }}
</a>
</div>
</div>
While jvandemo's answer will work, I think it can be improved slightly. By using setInterval
, it breaks the dependency injection convention that Angular follows and makes unit testing of the controller difficult.
Angular doesn't currently support setInterval
through its built-in services, but you can use the $timeout
service to produce the same functionality. I'd change the controller to this:
app.controller('MainCtrl', function($scope, $http, $timeout) {
// Function to get the data
$scope.getData = function(){
$http.get('style.css')
.success(function(data, status, headers, config) {
// Your code here
console.log('Fetched data!');
});
};
// Function to replicate setInterval using $timeout service.
$scope.intervalFunction = function(){
$timeout(function() {
$scope.getData();
$scope.intervalFunction();
}, 1000)
};
// Kick off the interval
$scope.intervalFunction();
});
这篇关于AngularJS ngcontroller需要定期重新加载数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!