在AngularJS指令中,是否可以跟踪li
元素的索引,并存储该索引值,以便可以将其与下一个悬停的li
元素的索引值进行比较?
指令:
app.directive('projectsHover', function($animate) {
return {
link: function(scope, element, attrs) {
element.css('position', 'absolute');
// offset each by 500px
var liTotal = element.parent().children().length;
for (var i = 0; i < liTotal; i++ ) {
element.css('left', i * 500 + 'px');
}
element.on("mouseover", mouseover);
var oldHoveredElement;
function mouseover(){
$animate.addClass(element, 'hovering');
// do some animation code here ...
oldHoveredElement = element; // doesn't keep track of the old element; always overwrites with currently hovered element. How can I store and reference the previously hovered on element?
console.log("oldHoveredElement.index(): ", oldElement.index());
console.log("element.index(): ", element.index());
if (oldHoveredElement.index() > element.index()) {
console.log("oldHoveredElement has a larger index value");
}
}
}
};
});
模板:
<ul>
<li projects-hover ng-repeat="project in projects" index="$index">
<div class="project-blurb">
<a>{{ project.title }}</a>
</div>
</li>
</ul>
答案 0 :(得分:0)
结束在父ul
中制作指令,以管理从子li
传入的旧索引和当前索引。
<ul projects-hover-manager>
<li project-hover ng-repeat="project in projects track by $index" ng-class="setClassName()">
<div class="project-blurb">
<a>{{ project.title }}</a>
<div ng-bind-html="project.description"></div>
</div>
</li>
</ul>
app.directive('projectsHoverManager', function(){
return {
controller: function($scope) {
var before, current, after;
var oldIndex, className;
this.giveClassName = function(index) {
if (oldIndex == index) {
console.log("oldIndex: ", oldIndex);
console.log("index: ", index);
console.log("currentLi");
className ="currentLi";
} else if (oldIndex > index) {
console.log("oldIndex: ", oldIndex);
console.log("index: ", index);
console.log("beforeLi");
className = "beforeLi";
} else if (oldIndex < index) {
console.log("oldIndex: ", oldIndex);
console.log("index: ", index);
console.log("afterLi");
className = "afterLi";
}
oldIndex = index;
return className;
};
}
};
});
app.directive('projectHover', function($animate) {
return {
require: '^projectsHoverManager',
link: function(scope, element, attrs, projectsHoverManagerCtrl) {
element.css('position', 'absolute');
// offset each by 500px
var liTotal = element.parent().children().length;
for (var i = 0; i < liTotal; i++ ) {
element.css('left', i * 500 + 'px');
}
// element.css('left', '500px');
element.on("mouseover", mouseover);
function mouseover(){
$animate.addClass(element, 'hovering');
// animation code ...
projectsHoverManagerCtrl.giveClassName(element.index());
scope.$apply();
}
};
});