Ank*_*nks 6 javascript json angularjs
我一直试图在互联网上找到一个解决方案,能够在设定的间隔时间更新我的$ http json请求,同时让它用新数据更新我的绑定.
我已经看到一些使用$ timeout的例子但是无法让它工作,只是想知道最好的方法是什么.由于我无法提出新请求,因此我无法解决新数据下拉后更新视图的问题.
这是我目前的构建.
app.js文件,这只显示了json的初始提取.
var myApp = angular.module('myApp', ['ngRoute']);
myApp.controller('MainCtrl', ['$scope', '$http',
function($scope, $http, $timeout) {
$scope.Days = {};
$http({
method: 'GET',
url: "data.json"
})
.success(function(data, status, headers, config) {
$scope.Days = data;
})
.error(function(data, status, headers, config) {
// something went wrong :(
});
}
]);
Run Code Online (Sandbox Code Playgroud)
HTML设置:
<ul ng-controller="MainCtrl">
<li class="date" ng-repeat-start="day in Days">
<strong>>{{ day.Date }}</strong>
</li>
<li class="item" ng-repeat-end ng-repeat="item in day.Items">
<strong>>{{ item.Name }}</strong>
</li>
</ul>
Run Code Online (Sandbox Code Playgroud)
我会用$timeout.
如你所知,$timeout回报承诺.因此,当承诺得到解决时,我们可以myLoop再次调用方法.
在下面的示例中,我们每隔10秒调用一次http.
var timer;
function myLoop() {
// When the timeout is defined, it returns a
// promise object.
timer = $timeout(function () {
console.log("Timeout executed", Date.now());
}, 10000);
timer.then(function () {
console.log("Timer resolved!");
$http({
method: 'GET',
url: "data.json"
}).success(function (data, status, headers, config) {
$scope.Days = data;
myLoop();
}).error(function (data, status, headers, config) {
// something went wrong :(
});
}, function () {
console.log("Timer rejected!");
});
}
myLoop();
Run Code Online (Sandbox Code Playgroud)
作为旁注:
当控制器被销毁时一定要打电话 $timeout.cancel( timer );
// When the DOM element is removed from the page,
// AngularJS will trigger the $destroy event on
// the scope.
// Cancel timeout
$scope.$on("$destroy", function (event) {
$timeout.cancel(timer);
});
Run Code Online (Sandbox Code Playgroud)
演示 Fiddle
| 归档时间: |
|
| 查看次数: |
7433 次 |
| 最近记录: |