Reputation:
Is there a better way to change an element height using angular js?
I'm doing it like:
function HomeCtrl ($scope) {
$('.banner').css('height', ($(window).height()) - $('.header').outerHeight());
}
Upvotes: 16
Views: 41013
Reputation: 9351
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.
It somewhat depends on what (and where) .header
is, but here's my idea:
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:
<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.
Upvotes: 35
Reputation: 8545
Don't make DOM manipulations in Controllers. Do it in Directives istead:
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>
Upvotes: 26