Javascript 服务中的角度范围更改不影响模板
我已经设置了一个可以在模板上显示状态消息的服务Javascript 服务中的角度范围更改不影响模板,javascript,angularjs,Javascript,Angularjs,我已经设置了一个可以在模板上显示状态消息的服务 .service('displayStatus', function () { var statusTime = 5000; var self = this; this.show = function ($scope, type, msg) { $scope.status = { type: type, msg: msg }
.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);
}
})
每当我想显示错误时,我只需调用displaystation.show($scope,'error','Uh oh!an error!')
。是设置超时给我带来了问题。虽然模板将根据我在“this.show”中所做的更改进行更新,但在等待5秒钟并试图隐藏它之后,这些更改不会应用,即使console.log显示我正在更改$scope
为什么我的更改没有显示出来 您需要将事件处理程序的主体包装在中,或者更好的是,使用该服务来完成超时,这将为您完成此操作。调用函数后,
$apply
触发一个$digest
循环,这是Angle检测模型更改的方式
.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);
}
})