使用$compile创建指令,并立即获得DOM属性
using $compile to create directive, and immediately get DOM properties
我创建了一个angularjs指令,它可以动态地创建多个指令,并将它们放在DOM的特定div
中。
在创建每个指令之后,我需要计算包装div的大小,以进行额外的操作。我看到在调用$compile()
动态创建指令后,它们还没有在DOM中。
我怎么能强迫angularjs在调用$compile()
后立即更新DOM,以便我可以在那之后玩DOM ?
这里有一个例子来展示我在做什么:
// This is my wrapping directive
angular.module('myModule').directive('wrapper', function($compile) {
return {
restrict: 'A',
template: '<div></div>',
scope: {
// the scope here is a list of objects that are the models for the inner directives to be created
innerModels: '='
},
link: function(scope, element, attrs) {
for (var i=0; i<innerModels.length; i++) {
var innerDirective = $compile('<inner-directive ng-model="innerModels['+i+']"></inner-directive>')(scope);
element.append(innerDirective);
// here I want to get the client size of the 'div' i created
var divHeight = element[0].clientHeight;
// divHeight == 0
// but after the page loads
// if i open the developer console when the page is finished loading, then the div does have a clientHeight value
}
}
};
});
angular.module('myModule').directive('innerDirective', function() {
return {
restrict: 'E',
template: '<span ng-bind-template="{{somethingFromModel}}"></span>',
scope: {
ngModel: '='
},
link: function(scope, element, attrs) {
// some logic...
}
};
});
注意:我这里没有使用jQuery(所以如果答案不包括jQuery解决方案我会很高兴)
简单的答案是在下一个摘要循环中运行您的代码,这将确保您的元素已绘制在DOM上,您可以使用$timeout
。
link: function(scope, element, attrs) {
for (var i=0; i<innerModels.length; i++) {
var innerDirective = $compile('<inner-directive ng-model="innerModels['+i+']"></inner-directive>')(scope);
element.append(innerDirective);
}
// here I want to get the client size of the 'div' i created
$timeout(function(){
//here you will get update height.
//play with rendered DOM here
})
// but after the page loads
// if i open the developer console, then the div does have a clientHeight value
}
相关文章:
- 将input复选框的DOM属性更改反映到innerHTML属性中
- 如何检测 DOM 属性中的更改
- setInterval 警报不会使用 dom 属性进行更新
- 使用简易XDM定期跨域报告DOM属性
- Angularjs 指令更新到 DOM 属性值的变化
- 在 React.js 中渲染 HTML 时没有额外的“data-reactid”DOM 属性
- 何时应该使用 on* DOM 属性与 on* HTML 属性
- 在 TypeScript 中从 DOM 属性转换为枚举
- 必应映射实体集合DOM属性
- 如何检索自定义DOM属性的值
- 使用Web动画制作DOM属性(scrollTop)的动画
- 使用ng-repeat创建DOM属性
- 如何从事件中获取DOM属性.目标,这样我就可以比较它们
- 使用javascript/jquery访问阴影DOM属性(聚合物)
- 使用$compile创建指令,并立即获得DOM属性
- 无法从动态加载的脚本读取DOM属性
- 读取Dom属性
- 绑定到Aurelia的只读DOM属性
- 自定义DOM属性在扩展中不可见
- 引导DOM属性- getElementById或$("“)