我已经创建了一个包含代码的 plunker,但由于某种原因,ng-click
无法在其中工作。
好吧,希望这足以说明我的问题。 http://plnkr.co/edit/ILbz7tMLpOgXyO0Dx6su?p=preview
因此,我尝试创建自己的简单 MessageService
,它是一个为下一个 $state
保存消息的服务(使用 ui-router)。
我创建了一个小指令,并将其包含在我的 plunker 中。
该指令在下一条路线上显示消息,但由于某种原因(我不知道),它不会触发 $timeout
函数,我在其中设置了 scope.feedback
为空。
正如您在我的 plunker 中看到的,我在指令模板上有一个 ng-show="feedback"
,并且我使用 MessageService 在指令 Controller 中填充它。 get()
用于检索消息。在我的链接函数中,我想将其设置为 null,以在一段时间后隐藏它。
模板:
<div ng-show="feedback" class="feedback">
<div class="alert feedback-message alert-success">{{feedback}}</div>
</div>
Controller 功能:
$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)
}
如果您需要更多信息,请告诉我。
最佳答案
该指令的
link
函数不仅会定期自动执行,它也不知道 statechangeSuccess
事件何时发生。它只会在指令渲染(编译)时运行。只需将其隐藏在 $stateChangeSuccess
本身上即可。
$scope.$on('$stateChangeSuccess', function () {
$scope.feedback = MessageService.get();
$timeout(function () {
$scope.feedback = null;
}, 1500)
});
或者只是在 Controller 上添加一个方法(或者您也可以将其添加到作用域上)
var _this = this;
$scope.$on('$stateChangeSuccess', function () {
$scope.feedback = MessageService.get();
$timeout(_this.hideFeedBack, 1500); //Invoke it here
});
_this.hideFeedBack = function(){
$scope.feedback = null;
}
并且还可以使用提供 Controller 实例的第四个参数在链接函数中访问它。
link: function (scope, el, attrs, ctrl) {
<强> Demo
关于javascript - 从链接函数修改指令 Controller 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27760494/