Javascript 使用setInterval()更新客户端(angularJS)上的值
我在客户端使用AngularJS作为值计算器。我想使用setInterval()每隔5分钟更新此计算器的主值 我的AngularJS代码是:Javascript 使用setInterval()更新客户端(angularJS)上的值,javascript,json,angularjs,setinterval,Javascript,Json,Angularjs,Setinterval,我在客户端使用AngularJS作为值计算器。我想使用setInterval()每隔5分钟更新此计算器的主值 我的AngularJS代码是: $http({method: 'GET', url: '../assets/sources.json'}).success(function(data) { $scope.values = data; // response data $scope.getSourceValue = function(){
$http({method: 'GET', url: '../assets/sources.json'}).success(function(data)
{
$scope.values = data; // response data
$scope.getSourceValue = function(){
if ($scope.source == "test") {
return $scope.values.test["last"]
} else if ($scope.source == "test1"){
return $scope.values.test1["last"]
} else if ($scope.source == "test2"){
return $scope.values["test2"]["last"]
} else {
return -1
};
} // getSource
}
在客户端:
<strong><h1> {{getSourceValue()|currency}}</strong></h1>
我将为其他人发布解决方案。 我的做法:
angular.module('test', [])
.controller('test', function($scope, $http, $filter, $interval) {
var stop;
if(!angular.isDefined(stop)) {
stop = $interval(function(){
$http({method: 'GET', url: '../assets/sources.json'}).success(function(data)
{
$scope.values = data; // response data
$scope.svalue = 0;
$scope.getSourceValue = function(){
if ($scope.source == "bitcoinaverage.com") {
$scope.svalue = $scope.values.bitcoinaverage["last"]
} else if ($scope.source == "bitstamp.net"){
$scope.svalue = $scope.values.bitstamp["last"]
} else if ($scope.source == "btc-e.com"){
$scope.svalue = $scope.values["btc-e"]["last"]
} else {
$scope.svalue = -1
};
} // getSource
});// /success()
}, 40000);
}
}); /*Controller*/
您可以提供json文件的内容吗?是否在
setInterval
中使用$scope.$apply()
来更新绑定?使用setInterval
可以使您脱离角度摘要。不,我真的不知道怎么做,我试着用setTimeInterval for JS,但没有用Angular(duh)。可能重复使用$timeout而不是setTimeOut在每次ajax调用中重新定义$scope.getSourceValue。将其移动到外部作用域,并更喜欢使用“this”aproach,仅当该函数与子控制器共享时才放入$scope。其他提示,控制器负责控制modelview交互。将收集的逻辑和数据资源放入服务中。:)
angular.module('test', [])
.controller('test', function($scope, $http, $filter, $interval) {
var stop;
if(!angular.isDefined(stop)) {
stop = $interval(function(){
$http({method: 'GET', url: '../assets/sources.json'}).success(function(data)
{
$scope.values = data; // response data
$scope.svalue = 0;
$scope.getSourceValue = function(){
if ($scope.source == "bitcoinaverage.com") {
$scope.svalue = $scope.values.bitcoinaverage["last"]
} else if ($scope.source == "bitstamp.net"){
$scope.svalue = $scope.values.bitstamp["last"]
} else if ($scope.source == "btc-e.com"){
$scope.svalue = $scope.values["btc-e"]["last"]
} else {
$scope.svalue = -1
};
} // getSource
});// /success()
}, 40000);
}
}); /*Controller*/