Mar*_*ijn 2 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);
}
});
}
}
});
Run Code Online (Sandbox Code Playgroud)
隐藏下拉指令:
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);
}
});
});
}
};
});
Run Code Online (Sandbox Code Playgroud)
后一条指令不起作用.我想要实现的是,当下拉列表外有点击事件时,下拉列表必须隐藏.
显示下拉列表适用于此代码,但下拉列表永远不会隐藏,我无法弄清楚原因.那么我需要做些什么来让我的"隐藏所有下拉菜单"开始工作?
该$(document).mouseup回调是运行"外"角,所以角不会注意到模式变革的事件处理程序.只需添加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(); // <<-----------------
}
});
});
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1844 次 |
| 最近记录: |