jQuery 使用 Angular JS 更改元素高度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18880735/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Change element height using Angular JS
提问by Murat ?orlu
Is there a better way to change an element height using angular js?
有没有更好的方法来使用 angular js 更改元素高度?
I'm doing it like:
我这样做:
function HomeCtrl ($scope) {
$('.banner').css('height', ($(window).height()) - $('.header').outerHeight());
}
回答by Fourth
Avoid jQuery all together. Use a directive and you can access the element and make adjustments to it. As a general rule of thumb, if you have brought in jQuery to help you do DOM manipulation, you are likely doing Angular wrong. Without a lot of context its hard to suggest a better implementation than what you have here.
一起避免使用jQuery。使用指令,您可以访问该元素并对其进行调整。作为一般经验法则,如果您引入了 jQuery 来帮助您进行 DOM 操作,那么您很可能在 Angular 上做错了。没有很多上下文,很难提出比这里更好的实现。
It somewhat depends on what (and where) .header
is, but here's my idea:
这在某种程度上取决于是什么(以及在哪里).header
,但这是我的想法:
jscript:
脚本:
var myApp = angular.module('myApp', []);
myApp.directive('banner', function ($window) {
return {
restrict: 'A',
link: function (scope, elem, attrs) {
var winHeight = $window.innerHeight;
var headerHeight = attrs.banner ? attrs.banner : 0;
elem.css('height', winHeight - headerHeight + 'px');
}
};
});
html:
html:
<div banner="250" class="banner">I'm a banner!</div>
Since I am not sure what header is, I just assume have it get passed in as an attribute. My best guess for that would be to grab its height and store it in a controller scope that is then watched by banner. This would make it somewhat responsive as well.
由于我不确定标头是什么,我只是假设它作为属性传入。我对此的最佳猜测是获取其高度并将其存储在控制器范围内,然后由横幅进行监视。这也会使它有些响应。
回答by Murat ?orlu
Don't make DOM manipulations in Controllers. Do it in Directives istead:
不要在控制器中进行 DOM 操作。改为在指令中执行:
angular.module('myApp', []).directive('banner', function() {
return function (scope, element, attrs) {
element.height($(window).height() - $('.header').outerHeight());
}
});
And in template:
在模板中:
<div banner>foo bar</div>