gpt4 book ai didi

javascript - 为什么我的指令的链接功能永远不会被调用?

转载 作者:搜寻专家 更新时间:2023-10-31 08:31:34 25 4
gpt4 key购买 nike

我有这个指令:

    hpDsat.directive('ngElementReady', [function() {
return {
restrict: "A",
link: function($scope, $element, $attributes) {
// put watches here.
console.log(" WHAT THE @#%*%$??? ");
$scope.$eval($attributes.ngElementReady);
}
};
}]);

我从未看到 console.log 的输出。我正在声明这样一个元素:

<div data-ng-element-ready="console.log(' ------------------------------- COMPILED! ')" data-ng-if="analysis.type" data-ng-show="showBasicHtml" data-ng-include="analysis.type+'Content.html'"></div>

是的,我在声明 div 元素所在的 Controller 之前声明指令。元素出现,ngShow 和 ngInclude 工作,加载模板中的任何东西也工作正常(更多指令、 Controller 、{{expressions}} 等)。

如果我用编译函数执行它,编译函数可以工作,但链接函数仍然不行:

    hpDsat.directive('ngElementReady', [function() {
return {
restrict: "A",
compile: function($element, $attributes) {
console.log("This I do see."); // THIS WORKS!!
return function($scope) {
// put watches here.
console.log("But not this. Why???"); // DOESN'T WORK!!
$scope.$eval($attributes.ngElementReady);
};
}
};
}]);

编译函数的console.log运行正常,但是返回的链接函数仍然没有执行。

知道为什么链接函数可能不会被触发吗?

最佳答案

错误可能出在其他地方。我在 jsfiddle 中尝试过第一个版本有效。

评估()

无论如何,您可能对 $scope.$eval() 的作用有误解:

$scope.$eval() 根据范围评估 angularjs 代码。 JavaScript 的 eval() 函数在 angularjs 中运行任意 js 代码是 $window.eval()。更多相关信息:Angular.js: How does $eval work and why is it different from vanilla eval?

我测试了与 Controller 隔离的指令:

<div data-ng-element-ready="console.log('COMPILED!')"></div>

和指令:

app.directive('ngElementReady', ['$window', function($window) {
return {
restrict: "A",
link: function($scope, $element, $attributes) {
console.log("Reached the link fn", $attributes);
$window.eval($attributes.ngElementReady);
}
};
}]);

我确实得到了值“reached the link fn”并且 $attributes 是正确的:

Reached the link fn Object { $$element={...}, $attr={...},  
ngElementReady="console.log('COMPILED!')", more...}

$window.eval() 返回 COMPILED!

here带 Controller 。

无论如何,使用eval() 来执行写在属性中的代码看起来很危险。任何人都可以修改 DOM 以在其中运行代码。至少确保它不会影响任何其他用户或服务器端。

使用 ng-if 重现问题

第一条评论后编辑:我尝试使 ng-if 表达式的计算结果为 false here这次它没有显示消息。这可能是因为为了评估 ng-if,你必须首先编译指令。否则,它只是 anuglarjs 不知道的代码。但是,因为它已从 DOM 中删除,所以它永远不会到达链接函数。

AngularJS 函数的执行顺序

一般来说,执行顺序是这样的(Josh David Miller explains it:

<div directive1>
<div directive2>
<!-- ... -->
</div>
</div>

现在 AngularJS 将通过按特定顺序运行指令函数来创建指令:

directive1: compile
directive2: compile
directive1: controller
directive1: pre-link
directive2: controller
directive2: pre-link
directive2: post-link
directive1: post-link

关于javascript - 为什么我的指令的链接功能永远不会被调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23719622/

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