我的任务是根据AngularJS应用程序中的元素宽度实现字体大小的变化。我的HTML代码是:
<div id="widthToCompareWidth" class="total">
<div class="total-row">
<div class="total-cell">
<div font-size-from-width="0" class="total-cell-wrap">
<div translate="TOTAL_1" class="total-label"></div>
<div class="total-value-wrap"><span ng-bind="ctrl.total1" class="total-value"></span></div>
</div>
</div>
<div class="total-cell">
<div font-size-from-width="1" class="total-cell-wrap">
<div translate="TOTAL_2" class="total-label"></div>
<div class="total-value-wrap"><span ng-bind="ctrl.total2" class="total-value"></span></div>
</div>
</div>
<div class="total-cell">
<div font-size-from-width="2" class="total-cell-wrap">
<div translate="TOTAL_3" class="total-label"></div>
<div class="total-value-wrap"><span ng-bind="ctrl.total3" class="total-value"></span></div>
</div>
</div>
<div class="total-cell">
<div font-size-from-width="3" class="total-cell-wrap">
<div translate="TOTAL_4" class="total-label"></div>
<div class="total-value-wrap"><span ng-bind="ctrl.total4"></span></div>
</div>
</div>
</div>
</div>
这个想法是将所有元素的宽度总和与'total-cell-wrap'类比较为父块的宽度,类为'total'。我在我的控制器中使用以下代码:
var widthToCompareWidth = document.getElementById('widthToCompareWidth').offsetWidth;
$scope.offsetsArray = [
0, 0, 0, 0
];
$scope.changeFont = false;
$scope.$watchCollection('offsetsArray', function (newVal, oldVal) {
if(newVal !== oldVal) {
var totalAmount = $scope.offsetsArray.reduce(function (sum, curr) {
if(!sum) sum = 0;
if(!curr) curr = 0;
return sum + curr;
}, 0);
(totalAmount > widthToCompareWidth) ? $scope.changeFont = true : $scope.changeFont = false;
}
})
并添加了以下指令:
(function () {
"use strict";
angular
.module('app')
.directive('fontSizeFromWidth', fontSizeFromWidth);
function fontSizeFromWidth() {
return {
restrict: 'A',
scope: {
fontSizeFromWidth: "=fontSizeFromWidth"
},
link: linkFn,
};
function linkFn(scope, element, attr, controller) {
scope.$watch(function () {
return scope.elementWidth = element[0].offsetWidth;
}, function(value) {
scope.$parent.offsetsArray[scope.fontSizeFromWidth] = scope.elementWidth;
});
scope.$watch('$parent.changeFont', function (newValue, oldValue) {
if(oldValue === false && newValue === true) {
element[0].classList.add('total-24');
} else if(oldValue === true && newValue === false) {
if(element[0].classList.contains('total-24')) {
element[0].classList.remove('total-24');
}
}
});
element.bind('load resize', function () {
scope.$apply();
});
}
}
})();
实际上,'total-24'类增加了较小的字体大小。
它似乎有效,但不完全正确 - 因为我知道,控制台中存在大量错误,连接到$ watch:
未捕获错误:[$ rootScope:infdig] 10 $ digest()迭代达成。中止! 观察者在最近5次迭代中被解雇:......
所以,问题是 - 我做错了什么,以及做这件事的正确方法是什么?
我的AngularJS版本是1.5.8。