gpt4 book ai didi

javascript - Angular JS - 评估时机

转载 作者:行者123 更新时间:2023-11-28 01:41:31 25 4
gpt4 key购买 nike

我在 angularjs 中遇到以下问题。我想使用一个 UI 库来注入(inject)一些 html 代码本身(Metro UI CSS),但我很难获得正确的执行顺序。

一个简单的例子:http://metroui.org.ua/hint.html

如果我在html中声明:

<span data-hint="My hint"></span>

UIjs 将创建提示显示所需的 html 元素。无需添加更多脚本代码。实际上,当您加载 js 时,会执行以下代码: $('[data-hint]').hint();

由于当我加载 JavaScript 时, Angular 创建的 html 不存在,因此它一开始根本不起作用。

我相信我需要一个 Angular Directive(指令)来解​​决问题(部分情况确实如此) - 我创建了 fowlling 指令:

app.directive('hints', function() {
return {
link: function() {$('[data-hint]').hint()}
};
});

以下内容确实有效,即使这是在 Angular 创建的 html 中:

<span hints data-hint="the text for my hint">test</span>

以下内容不起作用(至少它没有按照我想要的方式运行):

<span hints data-hint="{{something}}">Test</span>

提示文本将按字面显示 {{something}},而不是 Angular 表达式后面的任何内容。我已经尝试创建类似的模板,但结果仍然相同:

app.directive('hints', function() {
return {
template: '<span data-hint="{{something}}">Test</span>',
link: function() {$('[data-hint]').hint()}
};
});

任何有关如何解决该问题的提示将不胜感激。

最佳答案

主要问题似乎是,如果您在链接函数中附加hint(),jquery会在Angular评估它之前获取旧值。一种选择是将 $timeout(function(){..}) 包裹在 element.hint() 周围,但我已经太多地使用了这个 hack,而且它并没有无法解决另一个问题:当 $scope 更改时,提示需要更新(如果它依赖于 $scope)。为了解决这个问题,我们可以添加 $watch 函数并在需要时更新提示值。

所以,结论是:

/* This directive triggers automatically on data-hint as well */
app.directive('hint', function($timeout) {
return {
link: function(scope, element, arguments) {

/* set the value of the hint, then attach the metro-hint widget */
element.data('hint' , arguments.hint).hint();

/* watch for changes in the value so the hint gets updated */
scope.$watch(function(){
return arguments.hint;
}, function() {
element.data('hint' , arguments.hint);
});
}
};
});

(使用 jquery 1.10.2、jquery-ui 1.10.3 和 Angular 1.2.6 进行测试)

关于javascript - Angular JS - 评估时机,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20869811/

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