我正在尝试构建一个侧面导航菜单,但希望根据 DOM 的状态(即我的 DOM 中的 s)动态填充其项目。<section>
但是,我将一些ng-if
s 应用于<section>
基于通过 AJAX ( )检索的范围变量的各种 s。$http.get
因此,当指令被编译(或链接)时,这些范围变量还没有被检索到并且ng-if
s 还不稳定(它们被评估为好像变量是undefined
)。
主要 HTML
<my-sidenav></my-sidenav>
<!-- Bunch of other content and structure -->
<section id="foo1" class="sidenav-item">...</section>
<section id="foo2" class="sidenav-item">...</section>
<section id="foo3" class="sidenav-item" ng-if="fooVar1 === fooVar2">...</section>
<section id="foo4" class="sidenav-item">...</section>
<section id="foo5" class="sidenav-item" ng-if="fooVar3 !== fooVar4">...</section>
Sidenav HTML
<div>
<a ng-repeat="section in ctrl.sections track by section" href="#" ng-click="ctrl.scrollTo(section)">{{section}}</a>
</div>
指令定义
function mySidenav() {
return {
templateUrl: 'sidenav.html',
controller: function() {
var ctrl = this;
// After template URL is linked up
// !!! ng-if still not stable !!!
ctrl.$postLink = function() {
// Convert nodeList to array for easier manipulation
var nodeList = document.querySelectorAll('.sidenav-item');
var nodeArray = Array.prototype.slice.call(nodeList);
// Extract section id
ctrl.sections = nodeArray.map(function(el) {return el.id;});
};
ctrl.scrollTo = /*...*/
},
controllerAs: 'ctrl'
};
}
表达式稳定后 访问页面上 DOM 元素的最佳方式是什么?ng-if
我在想$timeout
,但真的不知道“安全值”是什么。
或者我可以/应该以某种方式使用$watch
?有没有办法ctrl.sections
动态更新?