11

アプリ内のすべての要素の非表示と表示の式を確認したいと思います。

引数を返すだけの関数で show ディレクティブをラップすることで、それができることはわかっています。

<div ng-show="catchShow(myShowExpr == 42)"></div>

ただし、アプリのすべての入力ですべての非表示/表示を監視したいのですが、上記では十分ではありません。

ngShow/ngHideディレクティブをオーバーロードすることもできますが、式を再評価する必要があります。

非常に単純なので、ソースを変更することもできます。

var ngShowDirective = ['$animator', function($animator) {
  return function(scope, element, attr) {
    var animate = $animator(scope, attr);
    scope.$watch(attr.ngShow, function ngShowWatchAction(value) {
      var fn = toBoolean(value) ? 'show' : 'hide';
      animate[fn](element);
      //I could add this:
      element.trigger(fn);
    });
  };
}];

その後、Google CDNを使用できませんでした...

誰もがこれを行うために考えられるより良い方法はありますか?

4

2 に答える 2

22

これが私が思いついたものです(CoffeeScript)

getDirective = (isHide) ->
  ['$animator', ($animator) ->
    (scope, element, attr) ->
      animate = $animator(scope, attr)
      last = null
      scope.$watch attr.oaShow, (value) ->
        value = not value if isHide
        action = if value then "show" else "hide"
        if action isnt last
          scope.$emit 'elementVisibility', { element, action }
          animate[action] element
        last = action
  ]

App.directive 'oaShow', getDirective(false)
App.directive 'oaHide', getDirective(true)

JavaScript に変換:

var getDirective = function(isHide) {

  return ['$animator', function($animator) {
    //linker function
    return function(scope, element, attr) {

      var animate, last;
      animate = $animator(scope, attr);
      last = null;

      return scope.$watch(attr.oaShow, function(value) {
        var action;
        if (isHide)
          value = !value;

        action = value ? "show" : "hide";

        if (action !== last) {
          scope.$emit('elementVisibility', {
            element: element,
            action: action
          });
          animate[action](element);
        }

        return last = action;
      });
    };
  }];
};

App.directive('oaShow', getDirective(false));
App.directive('oaHide', getDirective(true));
于 2013-05-07T02:12:42.250 に答える
1

アプローチする別の方法$watchは - の属性をngShow使用することですが、これはディレクティブ内で行う必要があります (既にカスタム ディレクティブを表示/非表示にしている場合に便利です)。

scope.$watch attrs.ngShow, (shown) ->
  if shown
    # Do something if we're displaying
  else
    # Do something else if we're hiding
于 2015-05-04T17:27:46.907 に答える