我已经创建了一个包含我的代码的plunker,但出于某种原因ng-click
在那里工作了。
好吧,希望这足以说明我的问题。 http://plnkr.co/edit/ILbz7tMLpOgXyO0Dx6su?p=preview
所以我尝试创建自己的简单MessageService
,这是一个为下一个$state
(使用ui-router)保存消息的服务。
我已经创建了一个小指令,我也已将其包含在我的plunker中。
该指令在下一个路由上显示消息,但由于某种原因(我不知道)它不会触发$timeout
函数,我将scope.feedback
设置为null。
正如你在我的plunker中看到的那样,我在指令模板上得到了一个ng-show="feedback"
,并且我在指令控制器中使用MessageService.get()
来填充它以检索消息。在我的链接函数中,我想将其设置为null,以便在一段时间后隐藏它。
模板:
<div ng-show="feedback" class="feedback">
<div class="alert feedback-message alert-success">{{feedback}}</div>
</div>
控制器功能:
$scope.$on('$stateChangeSuccess', function () {
$scope.feedback = MessageService.get();
});
链接功能:
if (scope.feedback != null) {
if (scope.feedback.type == 'success') {
scope.typeClass = 'alert-success';
} else if (scope.feedback.type == 'error') {
scope.typeClass = 'alert-danger';
}
$timeout(function () {
scope.feedback = null;
}, 1500)
}
如果您需要更多信息,请与我们联系。
答案 0 :(得分:1)
link
函数不会定期自动执行,也不知道statechangeSuccess
事件何时发生。它只会在指令呈现(编译)时运行。只需将其隐藏在$stateChangeSuccess
本身。
$scope.$on('$stateChangeSuccess', function () {
$scope.feedback = MessageService.get();
$timeout(function () {
$scope.feedback = null;
}, 1500)
});
或者只是在控制器上添加一个方法(或者你也可以在范围上添加它)
var _this = this;
$scope.$on('$stateChangeSuccess', function () {
$scope.feedback = MessageService.get();
$timeout(_this.hideFeedBack, 1500); //Invoke it here
});
_this.hideFeedBack = function(){
$scope.feedback = null;
}
并使用给出控制器实例的第4个参数在链接函数中访问它。
link: function (scope, el, attrs, ctrl) {
<强> Demo 强>