ng-class表达式不会动态更改

时间:2013-09-18 02:55:22

标签: javascript angularjs angularjs-directive

完整代码在这里: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元素指令。

1 个答案:

答案 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/