UI-Router - 根据状态变化动态显示和隐藏元素

时间:2015-09-22 15:10:43

标签: angularjs

我正面临一个问题,即我根据状态更改动态显示和隐藏按钮,但是对于按钮应该隐藏的情况,我会在按钮被隐藏之前观察到明显的延迟。

按钮本身设置为指令,如下所示:

指令

let appearance = UINavigationBar.appearance()
    appearance.translucent = false
    appearance.titleTextAttributes = [NSFontAttributeName: UIFont(name: "Chalkduster", size: 21)!]
    appearance.barTintColor = UIColor(red: 80/255, green: 185/255, blue: 225/255, alpha: 1)
    appearance.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()]

模板

angular.module('app').directive('myActionButton', function() {
  return {
    restrict: 'E',
    templateUrl: 'myActionButton.html',
    controller: function($scope, $rootScope, MyActionButton) {
      $scope.myActionButton = MyActionButton;
      return $rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) {
        return $scope.myActionButton.hide();
      });
    }
  };
});

服务

<md-button ng-show="myActionButton.visible" class="md-fab md-fab-bottom-right" aria-label="Add" ng-click="myActionButton.mainAction($event)">
  <md-icon class="material-icons">add</md-icon>
</md-button>

正如您所看到的,我在指令的控制器中使用绑定服务。我也在我的应用程序中使用绑定到ui-router加载的视图的其他控制器中的此服务。

在由ui-router加载的页面控制器上,我需要按钮显示,我注入我的服务然后调用

var MyActionButton;

MyActionButton = function() {
  var myActionButton;
  myActionButton = {};
  myActionButton.visible = false;
  myActionButton.mainAction = null;

  myActionButton.setMainAction = function(fn) {
    myActionButton.mainAction = fn;
    myActionButton.show();
  };

  myActionButton.clearMainAction = function() {
    myActionButton.mainAction = null;
    myActionButton.hide();
  };
  return myActionButton;
};

angular.module('app').service('MyActionButton', MyActionButton);

这反过来调用服务本身的show()。

一切正常,页面会在需要时显示按钮。但是对于不需要显示按钮的页面,我没有在页面控制器中对我的服务进行任何调用来隐藏按钮。

相反,我正在我的指令控制器中监听$ stateChangeStart事件,然后调用我的服务的clearMainAction函数。

对于不需要按钮的页面,这确实有效,但是当从显示按钮的页面转换时,状态更改完成后需要几秒钟才能隐藏。

另外,我应该提一下我在每个标签上使用角度素材及其md-tabs配置了ui-sref属性。

任何人都可以解释为什么我可能会看到按钮隐藏的延迟?

由于

更新

这是基于我共享的代码的代码集 - http://codepen.io/anon/pen/GpqLgL

从标签1到2或3点击时,您会看到按钮暂时显示,然后在短暂延迟后隐藏。

1 个答案:

答案 0 :(得分:1)

当css转换应用于元素时,问题与ngAnimate如何与核心指令(如ng-show)集成有关。

如果ngAmimate检测到css变换,它将经历一系列添加/删除其他类,以允许该元素执行在css中设置隐藏/显示动画的任何内容。

如果您希望元素突然隐藏/显示,您可以修改该元素的css并调整时间或完全删除动画。

或者您无法使用ng-show并通过切换类或设置内联显示样式来自行管理显示