为什么是范围。$ watch在Angular中通过$ parse assign设置值时不会被触发?

时间:2013-06-14 11:23:39

标签: javascript jquery angularjs angularjs-directive

我有两个指令。一个指令显示下拉列表,另一个指令必须在单击页面上的其他位置时隐藏下拉列表。

下拉指令:

app.directive('dropdown', function ($parse) {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            scope.$watch(attrs.ngShow, function (newVal, oldVal) {

                obj = angular.element(document.getElementById(attrs.dropdown));
                if (newVal) {

                    // hide all drodowns with this attribute                    $(document).find('[dropdown]').each(function (index) {
                    if ($(this).is(':visible')) {
                        var attrValue = $(this).attr('ng-show');
                        var model = $parse(attrValue);

                        model.assign(scope, false);
                    }
                });
            var offset = obj.offset();
            var new_top = offset.top + 30;
            var right = offset.left + obj.outerWidth() - element.width() + 10;

            element.css('left', right + 'px');
            element.css('top', new_top + 'px'); angular.element(element.children()[0]).css('margin-left', element.width() - 30 + 'px');
            element.show('size', {
                origin: ["top", "right"]
            }, 100);
            }
        });
}
}
});

隐藏下拉指令:

app.directive('hideAllPopups', function ($parse) {
    return {
        link: function (scope, element, attrs) {
            $(document).mouseup(function (e) {

                $(document).find('[dropdown]').each(function (index) {

                    if ($(this).is(':visible')) {
                        var attrValue = $(this).attr('ng-show');
                        var model = $parse(attrValue);

                        model.assign(scope, false);
                    }
                });
            });
        }
    };
});

后一条指令不起作用。我想要实现的是,当下拉列表外有点击事件时,下拉列表必须隐藏。

显示下拉列表适用于此代码,但下拉列表永远不会隐藏,我无法弄清楚原因。那么我需要做些什么来让我的“隐藏所有下拉菜单”开始工作?

fiddle

1 个答案:

答案 0 :(得分:5)

$(document).mouseup回调是一个在“Angular”外部运行的事件处理程序,因此Angular不会注意到模型更改。只需添加scope.$apply()即可使用:

link: function (scope, element, attrs) {
    $(document).mouseup(function (e) {
        $(document).find('[dropdown]').each(function (index) {
            if ($(this).is(':visible')) {
                var attrValue = $(this).attr('ng-show');
                var model = $parse(attrValue);
                model.assign(scope, false);
                scope.$apply();  // <<-----------------
            }
        });
    });
}