指令链接功能无权访问整个模板DOM [英] Directive link function does not have access to the entire template DOM
问题描述
我有一个指令,其中包含一个递归包含模板的模板。在我的指令链接函数中,我无法使用选择器获得完整的DOM。
I have a directive which has a template that recursively include a template. In my directive link function, I am unable to get the complete DOM with a selector.
这是我的指令。请注意,我的指令尝试在构造的所有.ui.dropdown div上调用dropdown()函数,因此将激活嵌套下拉列表。
Here is my directive. Notice that my directive try to call dropdown() function on all .ui.dropdown divs constructed so nested dropdown will be activated.
.directive("floatingDropdown", function() {
return {
restrict: 'E',
templateUrl: "scripts/Ui/FloatingDropdown.html",
replace: true,
scope: {
uiClass: '@',
model: '=ngModel',
optionTree: '='
},
link: function(scope, elem, attrs) {
scope.elemClass = scope.uiClass || "ui floating dropdown icon button";
$(elem).dropdown();
$(elem).find(".ui.dropdown").dropdown();
}
}
})
脚本/ Ui / FloatingDropdown.html包含嵌套的include。这会产生多个级别的下拉菜单
The scripts/Ui/FloatingDropdown.html contains a nested include. This creates multiple levels of dropdowns
<div class="{{elemClass}}">
<script type="text/ng-template" id="node_template.html">
<div class="ui dropdown" ng-if="option.options">
<span ><i class="dropdown icon"></i> {{option.value}}</span>
<div class="menu" ng-if="data.options">
<div class="item" ng-repeat="option in data.options" ng-include="'node_template.html'"></div>
</div>
</div>
<span ng-if="!option.options" ng-click="model=option">{{option}}</span>
</script>
<i class="dropdown icon"></i>
<div class="menu">
<div class="item" ng-repeat="option in optionTree.options" ng-include="'node_template.html'">
</div>
</div>
</div>
我的问题是$(elem).find(。ui.dropdown)找不到递归生成的div由ng-include
My problem is $(elem).find(".ui.dropdown") will not find the recursively generated divs by ng-include
推荐答案
通过尝试在指令的link()方法中进行DOM操作,你可以'重新尝试查询/修改尚未呈现的DOM的一部分。
By attempting to do DOM manipulation in a directive's link() method like that, you're trying to query/modify a part of the DOM that hasn't been rendered yet.
您需要将这些jquery调用推迟到稍后。你可以这样做:
You need to defer those jquery calls until later. You can do this using:
$scope.$evalAsync(function() {
// DOM code
});
或
$timeout(function() {
// DOM code
}, 0);
使用 $ evalAsync
将在运行期间运行表达式下一个 $ digest
循环,允许您在浏览器中呈现之前修改HTML。使用 $ timeout
将等到所有 $ digest
周期完成。
Using $evalAsync
will run the expression during the next $digest
cycle, will allow you to modify HTML before it's rendered in the browser. Using $timeout
will wait until all $digest
cycles are complete.
这篇关于指令链接功能无权访问整个模板DOM的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!