AngularJS,指令元素为空

AngularJS, directive element is null

本文关键字:元素 指令 AngularJS      更新时间:2023-09-26

我正在努力将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在渲染阶段之后执行,这就是它工作的原因。