簡體   English   中英

Angular JS-評估時間

[英]Angular JS - Evaluation Timing

我在angularjs中遇到以下問題。 我想使用一個本身注入一些html代碼的UI庫(Metro UI CSS),並且我難以正確地執行該命令。

一個簡單的例子: http : //metroui.org.ua/hint.html

如果我在html中聲明:

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

UIjs將創建提示顯示所需的html元素。 必須添加新的腳本代碼。 好吧,實際上,當您加載js時,將執行以下代碼:$('[data-hint]')。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()}
};
});

任何有關如何解決該問題的提示將不勝感激。

主要問題似乎是,如果在鏈接函數中附加了hint() ,則jquery會在angular對它進行評估之前采用舊值。 一種選擇是將$timeout(function(){..})包裹在element.hint() $timeout(function(){..})周圍,​​但是我已經使用了太多的技巧,它並不能解決另一個問題:當$scope時,提示需要更新$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進行了測試)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM