gpt4 book ai didi

angularjs - 无需 jQuery 即可访问自定义指令的子元素

转载 作者:行者123 更新时间:2023-12-02 23:36:58 29 4
gpt4 key购买 nike

我已经为下拉菜单编写了一个自定义指令。这些元素绝对定位在相对定位的父元素内,因此我需要获取下拉触发元素的高度,以便将实际菜单移动到其下方。触发器是指令元素的子元素。我想避免使用成熟的 jQuery,而是使用 Angular 的 jqLit​​e。

到目前为止,我的尝试包括将一个函数添加到指令链接函数内的范围(以便访问 element),但我无法链接 find ()children() 来查找子元素。

我的链接和 Controller :

link: function(scope, element, attrs) {
scope.clicked = false;
scope.positionDropdown = function() {
if (!scope.clicked) {
scope.clicked = true;
scope.buttonHeight = element[0].find('button').offsetHeight;
}
}
},
controller: function($scope) {
'use strict';
$scope.menuActive = false;
$scope.toggleMenu = function () {
$scope.positionDropdown();
$scope.menuActive = !$scope.menuActive;
};
}

这应该做的是,当第一次单击按钮时,范围变量 buttonHeight 应使用元素的高度来定义。相反,我在 Chrome 开发工具中收到错误:

TypeError: undefined is not a function
at Scope.scope.positionDropdown (http://localhost:3000/directives/dropdown/dropdown-directive.js:17:57)
at Scope.$scope.toggleMenu (http://localhost:3000/directives/dropdown/dropdown-directive.js:25:28)
at Parser.functionCall (http://localhost:3000/angular/angular.js:10656:21)
at http://localhost:3000/angular/angular.js:18838:17
at Scope.$get.Scope.$eval (http://localhost:3000/angular/angular.js:12518:28)
at Scope.$get.Scope.$apply (http://localhost:3000/angular/angular.js:12616:23)
at HTMLButtonElement.<anonymous> (http://localhost:3000/angular/angular.js:18837:21)
at http://localhost:3000/angular/angular.js:2810:10
at Array.forEach (native)
at forEach (http://localhost:3000/angular/angular.js:320:11)

这是我的模板:

<div class="dropdown" ng-class="{active: menuActive}">
<button ng-click="toggleMenu()">{{ngLabel}}<i ng-class="ngIcon" ng-if="ngIcon"></i></button>
<ul ng-show="menuActive" ng-style="{top: buttonHeight}"ng-transclude>
</ul>

我已经设置了一个断点来解决这个问题。 element[0] 可以工作,但是 find() 方法关闭后会出现 TypeError: undefined is not a functionelement[0].children(document.querySelector('button')) 也会出现相同结果的错误。为什么这些选择下拉菜单的方法不起作用?我如何才能在不诉诸 jQuery 且不将自己限制在页面上的单个下拉列表的情况下选择此选项?

最佳答案

我没有明白你的问题,但如果你想选择 Angular 中某个元素的子元素,你可以这样做:

    link:function(scope,elem,attr){

// to select parent of parent of current element :
elem.parent().parent();
// to select parent of current element :
elem.parent();
// to select Child(a) of current element :
elem.children('a');
// to select all Childs of current element :
elem.children();
// getting element height
elem.height();
// window height :
$(window).height();
// document height:
$(document).height();
// distance of your elem to top of the page :
$(window).scrollTop() + $(window).height();




}

关于angularjs - 无需 jQuery 即可访问自定义指令的子元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24168056/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com