簡體   English   中英

AngularJS,指令元素為null

[英]AngularJS, directive element is null

我正在將jQuery插件移植到AngularJS只是因為它看起來很有趣。 過去,當使用jQuery時,我使用jQuery來操縱DOM。 因此,我在jQuery中有一個函數可以加載插件,而該函數是在操作DOM。

現在,當使用AngularJS時,我已經讀到有針對該特定目的的directives ,但是我無法找到解決方案。

我有以下html:

<body class="officeui-space-no-margin officeui-space-no-padding">
    <!-- Defines the OfficeUI section. In this section, all the contents for the OfficeUI user interface will be written. -->
    <div ng-controller="OfficeUIController" id="OfficeUI">
        <div class="title officeui-align-center">
            <span>Here the title can go.</span>
        </div>

        <!-- Defines the main holder for the ribbon. -->
        <div id="ribbonHolder">
            <!-- Render the template for the ribbon. -->
            <ng-include src="'Partials/Templates/Ribbon/tabs.html'"></ng-include>
        </div>
    </div>

    <!-- Bottom scripts: Used for Initialization. -->
    <script type="text/javascript">
        // Initialize the 'ribbonHolder' element as a ribbon.
        $('#ribbonHolder').ribbon();
    </script>
</body>

您在這里看到我正在加載要渲染的模板,其內容可以在下面找到:

<ul role="tablist" class="officeui-space-no-margin officeui-space-no-padding">
    <!-- Render all the tabs in the collection. -->
    <tabs-container>
        <li role="tab" class="officeui-display-inline-block officeui-align-center" ng-repeat="tab in tabs">{{tab.Name|tabs}}</li>
    </tabs-container>
</ul>

在上面的模板中,我確實有一個元素tabs-container ,這應該是我的指令。 我有定義AngularJS內容的JavaScript,包括注冊此指令:

var officeUIApplication = angular.module('OfficeUI.Ribbon.Controllers', []);
officeUIApplication.directive('tabsContainer', function() {
    var functionLink = function(scope, element, attrs) {
        console.log(element.children());
    };

    return {
        restrict: 'E',
        link: functionLink
    };
});

據我對AngularJS的有限了解,我只是在學習它,它在變量functionLink ,我應該在該事件中處理將事件處理程序附加到特定部分的DOM。

但是在functionLink內部,我調用以下代碼:

console.log(element.children());

但是在控制台中,我確實看到該特定元素為空。 為什么會這樣,這是個好方法嗎?

我努力使它包括在jQuery中的另一種方法,以便僅在AngularJS完成工作后才執行代碼,但另一方面,我不喜歡該特定想法,如何創建jQuery插件傳遞選項和事件處理程序,還是不可能了,實際上我是在創建AngularJS插件嗎?

感謝您的回復。

嘗試這個:

officeUIApplication.directive('tabsContainer', function($timeout) {
    var functionLink = function(scope, element, attrs) {
         $timeout(function() { 
              element.ribbon();
         });
    };

    return {
        restrict: 'E',
        link: functionLink
    };
});

jQuery插件通常需要DOM才能正確初始化。 在角度上,沒有真正的DOM准備就緒概念。 $ timeout在渲染階段之后執行,這就是它起作用的原因。

暫無
暫無

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

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