gpt4 book ai didi

javascript - Angular 事件处理程序属性更改不会触发监听器

转载 作者:行者123 更新时间:2023-11-30 00:02:41 26 4
gpt4 key购买 nike

我正在使用 Angular 来触发下拉菜单,在这个应用程序的情况下,它会在显示下拉菜单之前加载它的内容。我想要实现的是能够将下拉指令添加到元素,但重要的是,我希望下拉列表出现在元素之后,而不是中,因为可能会使用各种不同的元素来触发此下拉菜单。

我已经完成了所有这些工作,但我觉得它不像我想要的那样 Angular 因为它似乎需要手动 $scope.$apply(),在我看来,如果我正在使用 Angular 的流程,那应该是不必要的。此外,由于这被用于显示悬停菜单,如果鼠标经过多个触发元素,Angular 会对多个应用调用感到不安。

HTML 的简化版本如下所示:

<div ng-app="example">
<div example-hover>
Hover me
</div>
</div>

使用以下 JS:

var app = angular.module('example', []);

angular.module("example")
.controller("exampleHoverController", function( $scope ) {
$scope.showHoverList = false;

$scope.setHoverList = function(value) {
console.log("Set hoverlist value: "+value);
this.showHoverList=value;
$scope.$apply();
}
});

angular.module("example")
.directive("exampleHover", function( $compile ) {
return {
restrict: "A",
template: '',
controller: 'exampleHoverController',
link: function( scope, element) {
element.after('<example-dropdown></example-dropdown>');
$compile(element.parent().find('example-dropdown'))(scope);

element.bind("mouseover", function() {
scope.showHoverList = true;
scope.setHoverList(true);
});
element.bind("mouseout", function() {
scope.showHoverList = false;
scope.setHoverList(false);
});
}
}
});

angular.module("example")
.directive("exampleDropdown", function() {
return {
restrict: 'E',
replace: true,
template: '<div ng-show="showHoverList">I should be visible when hovered!</template>',
controller: "exampleHoverController"
};
});

强制性 JSFiddle link .请注意,这是工作代码,我的问题是:当我更新 exampleHoverController 中的 Controller 属性时,如何在不需要调用 $scope.$apply 的情况下实现相同的目的?

我知道如果我提前知道我的所有数据,有更简单的方法可以实现这种效果,但这段代码的真实版本比这个例子做的要多得多,我需要能够附加将菜单悬停在任何元素上,然后在显示它时执行一些后台查询,所以如果不是这个确切的模式,我真的需要一些与此行为匹配的东西。

最佳答案

https://jsfiddle.net/z03huraq/32/

您可以在 exampleHover 指令上使用编译函数来:

  • 删除指令属性(否则会进入循环)
  • 并将2个鼠标事件直接添加到模板html中

    compile: function(){
    return {
    pre: function(scope, element, attributes, controller, transcludeFn){
    element.removeAttr("example-hover")
    .attr("ng-mouseover","mouseOver()")
    .attr("ng-mouseout","mouseOut()");
    $compile(element)(scope);
    },
    post: function(scope, element, attributes, controller, transcludeFn){
    element.after('<example-dropdown></example-dropdown>');
    $compile(element.parent().find('example-dropdown'))(scope);
    }
    }
    }

这将允许摘要循环确认事件的存在。

关于javascript - Angular 事件处理程序属性更改不会触发监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39767305/

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