[英]Angularjs view doesn't update
我正在尝试通过从服务中获取其数据的控制器来更新视图。 由于某些原因,当服务的数据更改时,视图不会更新。 我从这里的应用程序中提取了一个示例。 我尝试了各种绑定( $scope.time = TimerService.value
,使用$watch
包裹在函数中-不成功)。
请注意,在我的原始应用程序中,这是一个对象数组,并且对象的属性发生了变化。
-script.js-
var mod = angular.module('mymodule', []);
mod.service('TimerService', function() {
this.value = 0;
var self = this;
setInterval(function() {
self.value += 1;
}, 2000)
});
mod.controller('TimerCtrl', ['TimerService', '$scope', function(TimerService, $scope) {
$scope.time = TimerService.value;
$scope.$watch(function() {
return TimerService.value;
}, function(newValue) {
$scope.time = newValue;
}, true);
$scope.otherValue = '12345';
}]);
angular.element(document).ready(function() {
alert('start');
angular.bootstrap(document, ['mymodule']);
});
-index.html-
<!DOCTYPE html>
<html>
<head>
<script src="./angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body>
<div ng-controller="TimerCtrl">
<h1>- {{ time }}-</h1>
<h2>{{ otherValue }}</h2>
</div>
</body>
</html>
在花了一些时间反复试验之后,我终于找到了解决问题的方法。 在上面的示例(以及我的实际应用程序)中,数据在角度范围(控制器按钮单击,http请求等)之外发生了更改,这意味着摘要周期尚未开始。 如果我将代码更改为使用$timeout()
,那么它将起作用。 不幸的是,这并不能完全解决我在角度之外更改数据的问题(我想我也需要将其余部分集成到角度中)。
更新
我通过在服务中使用rootscope
在角度之外进行更改:
$rootscope.$apply(function() {
// perform variable update here.
self.value += 1;
});
这成功传播到视图。
尝试这个
$scope.time = TimerService.value;
if(!$scope.$$phase) {
$scope.$apply();
}
尝试
var app = angular.module('myApp', []);
var value = 0;
var timer = setInterval('Repeater()', 1000);
var Repeater = function () {
value++;
var scope = angular.element(document.getElementById('myApp')).scope();
console.log(scope);
scope.$apply(function () {
scope.time = value;
});
};
app.controller('TimerCtrl', ['$scope', function( $scope) {
}]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.