我已经设置了一个可以在模板上显示状态消息的服务。
.service('displayStatus', function ()
{
var statusTime = 5000;
var self = this;
this.show = function ($scope, type, msg)
{
$scope.status = {
type: type,
msg: msg
}
self.timer = setTimeout(function ()
{
self.hide($scope);
}, statusTime);
}
this.hide = function ($scope)
{
$scope.status = {
type: null,
msg: null
}
console.log('hid it', $scope);
}
})
每当我想要显示错误时,我只需拨打displayStatus.show($scope, 'error', 'Uh oh! An error!')
。这是setTimeout给我带来的问题。虽然模板将根据我在" this.show"中的更改进行更新,等待5秒并尝试隐藏它后,即使console.log显示I&I,也不会应用这些更改。 #39;改变$ scope。
为什么我的更改没有显示?
答案 0 :(得分:2)
您需要在$scope.$apply
中包装事件处理程序的主体,或者更好的是,使用$timeout
服务执行超时,这样做可以帮助您。调用您的函数后,$apply
会触发$digest
周期,这是角度检测模型更改的方式。
.service('displayStatus', function ($timeout)
{
var statusTime = 5000;
var self = this;
this.show = function ($scope, type, msg)
{
$scope.status = {
type: type,
msg: msg
}
self.timer = $timeout(function ()
{
self.hide($scope);
}, statusTime);
}
this.hide = function ($scope)
{
$scope.status = {
type: null,
msg: null
}
console.log('hid it', $scope);
}
})