1

リンク関数で要素の背景色を利用するカスタム ディレクティブがあります。

.directive('ktMouseover', function($log) {
  return {
    restrict: "AC",
    link: function(scope, elm, attrs) {
      if ($(".ie8, .ie7").length === 0) {
        console.log(elm.attr("class"));
        var oldBackgroundColor = elm.css("background-color") || elm.css("background")
          , colors = attrs["ktMouseover"].split("|")[0] || "#fec|#f55"
          , timings = attrs["ktMouseover"].split("|")[1] || "75|150"
          , newBackgroundColor = colors.split(":")[0] || "#fec"
          , newDangerColor = colors.split(":")[1] || "#f55"
          , fadeInTime = parseInt(timings.split(":")[0]) || 75
          , fadeOutTime = parseInt(timings.split(":")[1]) || 150;

        elm.mouseenter(function() {
          if (elm.hasClass("inactive")) return;
          $(this).animate({
            "backgroundColor":($(this).hasClass("danger") ? newDangerColor : newBackgroundColor)
          }, fadeInTime);
        }).mouseleave(function() {
          $(this).animate({
            "backgroundColor": (oldBackgroundColor ? oldBackgroundColor : "transparent")
          }, fadeOutTime);
        });
      }
    }
  };
})

HTML スニペット:

        <li class="{{child.type()}}"
            ng-include="'/partials/tree.html'"
            id="container_{{child.id()}}" 
            kt-mouseover=":#f55|75:150" 
            ng-click="getChildren(child)" 
            ng-repeat="child in vault.children()">
        </li>

これを最初にコーディングしたとき、タグに静的なクラス名を使用していました (CSS で background-color を設定する方法です)。これらのディレクティブに動的なクラス名を付ける必要がありますが、クラス名がまだ適用されていないため、突然要素から背景色を取得できなくなります。

AngularJSで慣用的にこれを達成するにはどうすればよいですか?

4

1 に答える 1

1

初期化せずに oldBackgroundColor 変数を宣言し、最初に mouseenter に設定するだけです。それが本当に最善の方法かどうかはわかりませんが、うまくいきます:

.directive('ktMouseover', function($log) {
  return {
    restrict: "AC",
    link: function(scope, elm, attrs) {
      if ($(".ie8, .ie7").length === 0) {

        // ***NOT INITIALIZED***
        var oldBackgroundColor
          , colors = attrs["ktMouseover"].split("|")[0] || "#fec|#f55"
          , timings = attrs["ktMouseover"].split("|")[1] || "75|150"
          , newBackgroundColor = colors.split(":")[0] || "#fec"
          , newDangerColor = colors.split(":")[1] || "#f55"
          , fadeInTime = parseInt(timings.split(":")[0]) || 75
          , fadeOutTime = parseInt(timings.split(":")[1]) || 150;

        elm.mouseenter(function() {
          if (elm.hasClass("inactive")) return;

          // ***INITIALIZED HERE INSTEAD***
          if (!oldBackgroundColor) oldBackgroundColor  = elm.css("background-color") || elm.css("background");
          $(this).animate({
            "backgroundColor":($(this).hasClass("danger") ? newDangerColor : newBackgroundColor)
          }, fadeInTime);
        }).mouseleave(function() {
          $(this).animate({
            "backgroundColor": (oldBackgroundColor ? oldBackgroundColor : "transparent")
          }, fadeOutTime);
        });
      }
    }
  };
})
于 2013-02-15T18:13:00.793 に答える