Javascript AngularJS视图未在模型更改时更新
我正在试图弄清楚Angular是如何工作的,并且在模型更改时很难更新视图 HTMLJavascript AngularJS视图未在模型更改时更新,javascript,angularjs,Javascript,Angularjs,我正在试图弄清楚Angular是如何工作的,并且在模型更改时很难更新视图 HTML 有什么想法吗?setTimout在angular之外执行。您需要使用$timeout服务才能工作: var app = angular.module('test', []); app.controller('TestCtrl', function ($scope, $timeout) { $scope.testValue = 0; $timeout(function()
有什么想法吗?
setTimout
在angular之外执行。您需要使用$timeout
服务才能工作:
var app = angular.module('test', []);
app.controller('TestCtrl', function ($scope, $timeout) {
$scope.testValue = 0;
$timeout(function() {
console.log($scope.testValue++);
}, 500);
});
原因是angular中的双向绑定使用脏检查。阅读angular的肮脏检查$scope.$apply()
启动一个$digest
循环。这将应用绑定$timeout
为您处理$apply
,因此建议在使用超时时使用该服务
本质上,绑定发生在$digest
周期中(如果发现值不同)。只需使用
这是你的代码修改。
正如上面提到的Ajay beniwal,你需要使用Apply开始消化
var app = angular.module('test', []);
app.controller('TestCtrl', function ($scope) {
$scope.testValue = 0;
setInterval(function() {
console.log($scope.testValue++);
$scope.$apply()
}, 500);
});
不要使用
$scope.$apply()
angular已经使用了它,它可能会导致此错误
$rootScope:inprog操作已在进行中
如果您使用两次,请使用
$timeout
或interval,除了下面的答案之外,如果您仍然要使用settimeout,则必须使用scope.$apply()$scope.$apply()是我需要的。我正在处理的项目中的模型在用户交互后更新。我实际上没有使用超时或间隔,但知道如何在将来使用它们是很好的。谢谢你的回答!这是一篇有趣的文章,你可以从中获得更多关于美元的信息,迭戈·维埃拉的答案更好。经验法则是:只要有可能,使用Angular的提供商/服务,他们自己应用。在我写评论时,没有任何$Interval,只是将其包装到setInterval顺便说一句。此外,它也不是这样保存它的外观:阅读更多:这是一个黑客,Angular有自己的计时器,$interval应改为用于更新Watchers Read my comments Upper此方法不安全,因为它将在给定的时间间隔内继续更新模型。。。
var app = angular.module('test', []);
app.controller('TestCtrl', function ($scope, $timeout) {
$scope.testValue = 0;
$timeout(function() {
console.log($scope.testValue++);
}, 500);
});
var app = angular.module('test', []);
app.controller('TestCtrl', function ($scope, $interval) {
$scope.testValue = 0;
$interval(function() {
$scope.testValue++;
}, 500);
});
var app = angular.module('test', []);
app.controller('TestCtrl', function ($scope) {
$scope.testValue = 0;
setInterval(function() {
console.log($scope.testValue++);
$scope.$apply()
}, 500);
});