Angular JS - 评估时间

时间:2014-01-01 14:48:23

标签: javascript jquery html angularjs

我在angularjs中遇到以下问题。我想使用一个自己注入一些HTML代码的UI库(Metro UI CSS),我在处理执行顺序方面遇到了麻烦。

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

如果我在html中声明:

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

UIjs将创建提示显示所需的html元素。必须添加Nofurther脚本代码。实际上当你加载js时,执行以下代码:$(&#39; [data-hint]&#39;)。hint();

由于在我加载javascript时,角度创建的html不存在,所以它根本不起作用。

我相信我需要一个角度指令来解​​决问题(以及它的部分) - 我创建了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}}而不是角度表达式背后的任何内容。我已经尝试过创建模板,但结果仍然相同:

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

非常感谢任何关于如何解决这个问题的提示。

1 个答案:

答案 0 :(得分:1)

主要问题似乎是如果你在链接函数中附加hint(),jquery会在angular评估之前获取旧值。一种选择是将$timeout(function(){..})包裹在element.hint()周围,但我已经使用了太多的黑客攻击,并且它没有解决另一个问题:当$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和角度1.2.6测试)