0

完整代码在这里: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 鼠标进入时显示,鼠标离开时隐藏

问题:似乎 ng-class 风格永远不会改变。

补充:一开始想改变指令中div.state-box的样式,但是不知道如何获取指令中的div.state-box元素。

4

1 回答 1

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/

于 2013-09-18T03:02:31.340 回答