Название может не объяснить, чего я пытаюсь достичь, поэтому я подробно рассмотрю здесь. У меня есть директива, которая ограничена именем класса CSS (в этом примере flex-wrap). Но этот класс не применяется к элементу, пока у нас фактически не будет данных.Директива AngularJS C с использованием ng-класса
HTML, для этого выглядит следующим образом:
<div class="row" ng-class="{ 'loading': !controller.loadingRecent, 'flex flex-vertical flex-wrap': controller.recent.length }">
<div class="col-md-12 row-title">
<h1>Recent orders</h1>
</div>
<div class="col-xs-12" ng-if="!controller.recent.length">
<div alert type="danger">
No records have been found that match your search.
</div>
</div>
<div class="col-md-4 tile-lg" ng-repeat="order in controller.recent" tile>
<a class="box-shadow" id="{{ order.orderNumber }}" ui-sref="viewOrder({ orderNumber: order.orderNumber })" coloured-tile>
<div class="text">
<p>
<strong>{{ order.account.accountNumber }}</strong><br />
{{ order.account.name }}<br />
{{ order.raisedBy }}<br />
{{ order.orderNumber }}<br />
{{ controller.getDescription(order) }}<br />
</p>
</div>
</a>
</div>
Как вы можете видеть, прогибается классы не применяются до нашего recent.length не больше 0. То, что я хотел бы случиться заключается в том, что когда у нас есть записи, применяется класс CSS, поэтому возникает угловая директива, связанная с этим классом.
Вместо этого он ничего не делает на данный момент. Кто-нибудь знает, как я могу получить мою директиву?
Вот моя директива, просто чтобы вы ее увидели.
.directive('flexWrap', ['$window', '$timeout', function ($window, $timeout) {
// Sets the height of the element
var setHeight = function (element) {
// Declare our variables
var row = element.parent().parent(),
height = 630;
// If our row is a row
if (row.hasClass('row')) {
// Get the height of the rest of the items
height = height - getHeight(row);
}
console.log('height = ' + height);
// Set our elements height
element.css('height', height + 'px');
console.log('we are about to set the width');
// After we set the height, set the width
setWidth(element);
}
// Gets the height to minus off the total
var getHeight = function (element) {
// Declare our variables
var height = 0,
children = element.children(),
loopChildren = element.hasClass('row');
// Loop through the element children
for (var i = 0; i < children.length; i++) {
// Get the child
var child = angular.element(children[i]);
// If the child is not a column
if (!child.hasClass('columns')) {
// If we need to loop the children
if (loopChildren) {
// Get the height of the children
height += getHeight(child);
// Otherwise
} else {
// Add the height of the child to
height += child[0].offsetHeight;
}
}
}
// Return our height
return height;
};
// Sets the width of the element
var setWidth = function (element) {
// After a short period
$timeout(function() {
// Get our last child
var children = element.children(),
length = children.length,
lastChild = children[length - 1];
// Work out the width of the container
var position = element[0].getBoundingClientRect(),
childPosition = lastChild.getBoundingClientRect(),
width = childPosition.left - position.left + childPosition.width;
var style = $window.getComputedStyle(lastChild, null);
console.log(style.getPropertyValue('width'));
console.log('--------------------------------');
console.log(lastChild);
console.log(position);
console.log(childPosition);
console.log(width);
console.log('--------------------------------');
console.log('width = ' + width);
// Apply the width to the element
element.css('width', width + 'px');
}, 500);
};
// Resize the container
var resize = function (element, width) {
// If our width > 992
if (width > 992) {
// Resize our element
setHeight(element);
// Otherwise
} else {
// Set our element width and height to auto
element.css('height', 'auto');
element.css('width', 'auto');
}
};
return {
restrict: 'C',
link: function (scope, element) {
// Get our window
var window = angular.element($window),
width = $window.innerWidth;
// Bind to the resize function
window.bind('resize', function() {
// After half a second
$timeout(function() {
// Get the window width
width = $window.innerWidth;
// Resize our element
resize(element, width);
}, 500);
});
// Initial resize
resize(element, width);
}
};
}]);
У меня было впечатление, что трансляция была плохой идеей? – r3plica
@ r3plica, независимо от того, есть он или нет, не имеет отношения к этому вопросу - но это один из вариантов. Обсуждение того, является ли это хорошей или плохой идеей, является более широким, чем мой ответ. Дело в том, что 'ng-class' работает не так, как вы ожидали –
Достаточно справедливо, но я надеюсь, что ответы будут отвечать« лучшей практикой », а не указывать на плохие практики? – r3plica