AngularJS,指令元素为空
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在渲染阶段之后执行,这就是它工作的原因。
相关文章:
- 指令的模板必须只有一个根元素:With restrict E&替换true
- 在元素指令上添加 css
- replace:true 如何与元素指令一起使用
- 防损层,从角度元素指令传递属性指令
- 角度:在元素指令上添加属性指令
- 如何在 angularjs 中验证元素指令
- 删除对象时执行元素指令动画的角度方式
- 从元素指令中的路由提供程序获取参数
- 基于会话服务的隐藏/显示元素指令-AngularJS
- AngularJS:从控制器中访问元素指令的属性
- 自定义元素指令和属性
- 如何在元素指令上使用ng-if来有条件地调用模块
- 将属性指令传递给元素指令
- 如何在AngularJS中以编程方式计算HTML元素(指令)的属性名
- 正在包装集合指令中元素指令的模板
- 无法正确使用元素指令
- Angularjs嵌套元素指令
- 使用 AngularJS 在选择元素指令中触发消息“onfocusleave”的“console.log”
- Angular自定义元素指令没有显示在屏幕上
- 带ng-init的AngularJS元素指令在视图渲染之前运行