Reputation: 2259
I have a custom directive that makes use of the background color of the element in the link function:
.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 snippet:
<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>
When I initially coded this, I was using a static class name for the tag (and that's how the background-color is set in my css). Now I have a need for these directives to have a dynamic class name, which suddenly makes it impossible to grab the background-color from the element, as the class name hasn't been applied to it yet.
How do I accomplish this idiomatically in AngularJS?
Upvotes: 1
Views: 4190
Reputation: 2259
Just declare the oldBackgroundColor variable without initializing it and set it in the mouseenter the first time. I don't know if that is really the best way to go about it, but it works:
.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);
});
}
}
};
})
Upvotes: 1