完整代码在这里:http://jsfiddle.net/yougen/duUsr/
查看:
<div ng-controller="MyCtrl" ng-app="app">
<div class="deal" deal-over>
<div class="deal-img">
<a href="/somewhere">
<img src="path/to/img" alt="should add a img">
</a>
<div class="state-box" ng-class="{dealOver:dealOver,dealOut:dealOut}">
<a href="/target-deal">Here show tips when hover</a>
</div>
</div>
</div>
</div>
指令:
app.directive('dealOver', function () {
return {
restrict: 'A',
link: function (scope, elem, attrs) {
elem.bind('mouseenter', function () {
scope.dealOver = true;
scope.dealOut = false;
//how to find div.state-box element from elem? elem.find('.state-box') not work
//elem.css({"opacity":0.9,"display":"block"});
});
elem.bind("mouseleave", function () {
scope.dealOver = false;
scope.dealOut = true;
});
}
};
});
目标::div.state-box显示当mouseenter,在mouseleave时隐藏
问题:似乎ng-class风格永远不会改变。
添加:在开头,我想更改指令中div.state-box的样式,但我不知道如何获取div.state-box元素指令。
答案 0 :(得分:4)
你必须让Angular知道你已经更新了范围。
通过将函数传递给scope.$apply
:
link: function (scope, elem, attrs) {
elem.bind('mouseenter', function () {
scope.$apply(function () {
scope.dealOver = true;
scope.dealOut = false;
});
});
elem.bind("mouseleave", function () {
scope.$apply(function () {
scope.dealOver = false;
scope.dealOut = true;
});
});
}
这是你的小提琴:http://jsfiddle.net/duUsr/7/