[英]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.