:
그것은 같은 것을 보일 것 그리고
.directive('adjustHeight', function ($timeout, $window) {
function adjustHeight(elem) {
// Do stuff - adjust the height
}
return {
restrict: 'A',
scope: {
data: '='
},
link: function postLink(scope, elem, attrs) {
var resizeListener = function (evt) {
adjustHeight(elem);
};
/* Adjust height on window resize */
$window.addEventListener('resize', resizeListener);
/* Adjust height when data changes
* (if necessary add an extra property for when being visible) */
scope.$watchCollection('data', function (newValue, oldValue) {
if (newValue.length === oldValue.length) {
/* Maybe you don't need to re-adjust the height
* if the number of elements hasn't changed */
return;
}
/* Wrapping the function inside a $timeout will ensure that
* the code is executed after the next browser rendering
* (thus after the modified list has been processed by ngRepeat) */
$timeout(function() { adjustHeight(elem); });
});
/* Make sure to clear the window-resize listener,
* once the element is removed */
scope.$on('$destroy', function() {
$window.removeEventListener('resize', resizeListener);
});
}
};
});
를, 당신은 다음과 같이 사용할 수 있습니다 :
<div ng-if="someCondition" adjust-height data="items">
<ul>
<li ng-repeat="item in items">{{item.property}}</li>
</ul>
</div>
나는 지침을 제안 할 예정이었습니다. 그러나 메소드가 재사용해야하는 경우가 아니면 지시문이 과도하게 사용됩니다. – joseym
@joseym : 나는 어떻게 (또는 어떤면에서) 그것이 과잉 일 수 있다고 생각하지 않는다. 재사용 이외에도, 여기서 핵심은 기능의 캡슐화입니다. 지시어에 싸여 있지 않다면 컨트롤러에 이벤트를'window.onResize'에 첨부해야합니다. 서비스가 가능할 수도있는 다른 코드는 데이터를 가져 오면 크기가 조정될 것입니다. 청취자의 등록을 취소하기 위해 엘리먼트가 페이지에서 제거 될 때. – gkalpak
@joseym : 이것은 여러 가지 이유로 매우 나쁩니다 (지금은 그렇게 나쁘지는 않지만 앱이 성장하기 시작하면 ...) : 1. 컨트롤러에서 DOM/창 조작. 2. 코드가 흩어져 있고 한 곳이 아닌 것 같습니다. 3. 선언적이지 않습니다 (보기를 보면서 무슨 일이 일어나는지 알지 못합니다. 컨트롤러에서 무엇이 진행되고 있는지 검색해야합니다). 4. 테스트 할 수 없습니다. (저는 Angular가 ** 제작 된 것이 아니라고 생각합니다.) – gkalpak