从链接函数修改指令控制器变量

Modify directive controller variable from link function

本文关键字:指令控制器 变量 修改 函数 链接      更新时间:2023-09-26

我已经创建了一个包装了代码的 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)
}    

如果您需要更多信息,请告诉我。

指令

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) {

演示