[英]In Angularjs, how do I review the DOM after a route change?
在我的应用程序中,我使用ng-view
切换出我的视图。 我需要操纵诸如更改宽度和位置之类的元素。 当我尝试在控制器上使用它时,正如我所料,我Unable to get property 'setAttribute' of undefined or null reference
。
我知道这种情况正在发生,因为JS不知道DOM已更改。
由于我正在运行一些繁重的插件以在Windows 8中使用SQLite,因此我不能发布太多代码。
这是我的模板正在加载到ng-view
<div id="productslist" class="container">
<div class="product" ng-repeat="product in products">
<div class="details">
<img src="img/detail-list-back.png" class="texture" />
<div class="heading">
<p class="title">{{product.name}}</p>
<img src="img/products/title-shadow.png" class="title-shadow"/>
</div>
<div class="text">
<div class="text-container">
<p class="intro" ng-hide="product.intro == null">{{product.intro}}</p>
<p class="title">Curves</p>
{{product.prodText}}
</div>
</div>
</div>
<div class="image" style="background-image:url('img/products/nanoslim-bkg.jpg')"></div>
</div>
</div>
我的一些角度。 for循环中断,因为它不知道这些部分是否存在:
var totalProd = res.rows.length;
var windowW = window.innerWidth;
var sections = document.querySelectorAll('#productslist .product');
var textArea = document.querySelectorAll('#productslist .text');
document.getElementById('productslist').setAttribute('style', 'width:' + (windowW * totalProd) + 'px');
for (var i = 0; i < sections.length; i++) {
sections[i].setAttribute('style', 'width:' + windowW + 'px');
}
其他一切正常。 我正在尝试通过使用ng-style来绕过此操作,但那里存在问题。
在有角度的情况下,应尽可能在指令中进行DOM操作。 这是将宽度设置为窗口宽度的示例:
.directive('fullWidth', function() {
function link(scope, element, attrs) {
var windowW = window.innerWidth;
element.css({width: windowW + 'px'});
}
return {
link: link
};
});
现在在您看来
<div class="product" full-width ng-repeat="product in products">
假设每个不同的视图都有一个不同的控制器,则您的DOM可能需要比控制器花费更多的时间来加载,从而导致Unable to get property 'setAttribute' of undefined or null reference.
您可以将DOM选择器语句放入$ timeout语句中 ,延迟1或2秒,这将使DOM有足够的时间加载并避免任何此类空引用问题。 像这样的东西:
myapp.controller("mycontroller"), function($scope, $timeout) {
$timeout(function() {
$("your-dom-selector").setAttribute("height", 500px);
}, 2000);
});
或者,更好的方法是使用广播模型,在该模型中,您可以跟踪路线更改事件,并且一旦路线更改事件成功,您就可以广播事件,并提供必要的详细信息,这些信息可以由相应的控制器捕获。 。
前一种方法易于使用,后一种是标准方法,并且保证没有错误。
$ timeout的更多详细信息在这里
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.