AngularJS - 지시 크기에 바인딩
지시의 크기가 조정되면 어떻게 통지합니까?난 시도했다.
element[0].onresize = function() {
console.log(element[0].offsetWidth + " " + element[0].offsetHeight);
}
하지만 그것은 그 기능을 부르지 않습니다.
(function() {
'use strict';
// Define the directive on the module.
// Inject the dependencies.
// Point to the directive definition function.
angular.module('app').directive('nvLayout', ['$window', '$compile', layoutDirective]);
function layoutDirective($window, $compile) {
// Usage:
//
// Creates:
//
var directive = {
link: link,
restrict: 'EA',
scope: {
layoutEntries: "=",
selected: "&onSelected"
},
template: "<div></div>",
controller: controller
};
return directive;
function link(scope, element, attrs) {
var elementCol = [];
var onSelectedHandler = scope.selected();
element.on("resize", function () {
console.log("resized.");
});
$(window).on("resize",scope.sizeNotifier);
scope.$on("$destroy", function () {
$(window).off("resize", $scope.sizeNotifier);
});
scope.sizeNotifier = function() {
alert("windows is being resized...");
};
scope.onselected = function(id) {
onSelectedHandler(id);
};
scope.$watch(function () {
return scope.layoutEntries.length;
},
function (value) {
//layout was changed
activateLayout(scope.layoutEntries);
});
function activateLayout(layoutEntries) {
for (var i = 0; i < layoutEntries.length; i++) {
if (elementCol[layoutEntries[i].id]) {
continue;
}
var div = "<nv-single-layout-entry id=slot" + layoutEntries[i].id + " on-selected='onselected' style=\"position:absolute;";
div = div + "top:" + layoutEntries[i].position.top + "%;";
div = div + "left:" + layoutEntries[i].position.left + "%;";
div = div + "height:" + layoutEntries[i].size.height + "%;";
div = div + "width:" + layoutEntries[i].size.width + "%;";
div = div + "\"></nv-single-layout-entry>";
var el = $compile(div)(scope);
element.append(el);
elementCol[layoutEntries[i].id] = 1;
}
};
}
function controller($scope, $element) {
}
}
})();
범위를 사용합니다.맞춤형 시계 기능이 있는 $watch:
scope.$watch(
function () {
return [element[0].offsetWidth, element[0].offsetHeight].join('x');
},
function (value) {
console.log('directive got resized:', value.split('x'));
}
)
당신은 일반적으로 요소의 특성을 관찰하기를 원할 것입니다.offsetWidth
그리고.offsetHeight
특성.AngularJS의 최신 버전에서는 다음을 사용할 수 있습니다.$scope.$watchGroup
링크 기능:
app.directive('myDirective', [function() {
function link($scope, element) {
var container = element[0];
$scope.$watchGroup([
function() { return container.offsetWidth; },
function() { return container.offsetHeight; }
], function(values) {
// Handle resize event ...
});
}
// Return directive definition ...
}]);
그러나 이러한 방식으로 요소 속성을 직접 관찰하면 업데이트 속도가 상당히 느릴 수 있습니다.
지시에 보다 반응하기 위해 다음을 사용하여 새로 고침 빈도를 줄일 수 있습니다.$interval
. 다음은 구성 가능한 밀리초 속도로 요소 크기를 확인할 수 있는 재사용 가능한 서비스의 예입니다.
app.factory('sizeWatcher', ['$interval', function($interval) {
return function (element, rate) {
var self = this;
(self.update = function() { self.dimensions = [element.offsetWidth, element.offsetHeight]; })();
self.monitor = $interval(self.update, rate);
self.group = [function() { return self.dimensions[0]; }, function() { return self.dimensions[1]; }];
self.cancel = function() { $interval.cancel(self.monitor); };
};
}]);
이러한 서비스를 사용하는 지침은 다음과 같습니다.
app.directive('myDirective', ['sizeWatcher', function(sizeWatcher) {
function link($scope, element) {
var container = element[0],
watcher = new sizeWatcher(container, 200);
$scope.$watchGroup(watcher.group, function(values) {
// Handle resize event ...
});
$scope.$on('$destroy', watcher.cancel);
}
// Return directive definition ...
}]);
통화 내용을 메모해 둡니다.watcher.cancel()
에서$scope.$destroy
이벤트 핸들러(event handler); 이렇게 하면$interval
인스턴스는 더 이상 필요하지 않을 때 삭제됩니다.
JSFiddle의 예는 여기에서 찾을 수 있습니다.
다음은 수행해야 할 작업에 대한 샘플 코드입니다.
APP.directive('nvLayout', function ($window) {
return {
template: "<div></div>",
restrict: 'EA',
link: function postLink(scope, element, attrs) {
scope.onResizeFunction = function() {
scope.windowHeight = $window.innerHeight;
scope.windowWidth = $window.innerWidth;
console.log(scope.windowHeight+"-"+scope.windowWidth)
};
// Call to the function when the page is first loaded
scope.onResizeFunction();
angular.element($window).bind('resize', function() {
scope.onResizeFunction();
scope.$apply();
});
}
};
});
$watch를 사용하여 요소의 크기/위치 변경을 탐지할 수 있는 유일한 방법은 $interval 또는 $timeout과 같은 방법을 사용하여 스코프를 지속적으로 업데이트하는 경우입니다.가능하면 비용이 많이 드는 작업이 될 수 있고, 앱 속도가 정말 느려질 수 있습니다.
요소의 변화를 감지할 수 있는 한 가지 방법은requestAnimationFrame
.
var previousPosition = element[0].getBoundingClientRect();
onFrame();
function onFrame() {
var currentPosition = element[0].getBoundingClientRect();
if (!angular.equals(previousPosition, currentPosition)) {
resiszeNotifier();
}
previousPosition = currentPosition;
requestAnimationFrame(onFrame);
}
function resiszeNotifier() {
// Notify...
}
이것을 보여주는 플렁크가 있습니다.당신이 상자를 옮기는 한, 그것은 빨간색으로 남아있을 것입니다.
http://plnkr.co/edit/qiMJaeipE9DgFsYd0sfr?p=preview
엘리엘의 대답을 약간 변형한 것이 제게는 통했습니다.명령어.js:
$scope.onResizeFunction = function() {
};
// Call to the function when the page is first loaded
$scope.onResizeFunction();
angular.element($(window)).bind('resize', function() {
$scope.onResizeFunction();
$scope.$apply();
});
불러봅니다
$(window).resize();
내 앱 안에서.js.지시서의 d3 차트는 이제 컨테이너를 채우도록 크기가 조정됩니다.
다음은 이 지침에 대한 나의 의견입니다(사용).Webpack
번들로 제공):
module.exports = (ngModule) ->
ngModule.directive 'onResize', ['Callback', (Callback) ->
restrict: 'A'
scope:
onResize: '@'
onResizeDebounce: '@'
link: (scope, element) ->
container = element[0]
eventName = scope.onResize || 'onResize'
delay = scope.onResizeDebounce || 1000
scope.$watchGroup [
-> container.offsetWidth ,
-> container.offsetHeight
], _.debounce (values) ->
Callback.event(eventName, values)
, delay
]
언급URL : https://stackoverflow.com/questions/21170607/angularjs-bind-to-directive-resize
'programing' 카테고리의 다른 글
Mysql 데이터 유형 열거 열에 새 값 추가 (0) | 2023.10.24 |
---|---|
동적양식명속성동적양식명속성동적양식명속성Angularjs Angularjs Angularjs (0) | 2023.10.24 |
getline() vs. fgets(): 메모리 할당 제어 (0) | 2023.10.24 |
SELECT 결과에서 긴 텍스트 필드 길이 제한 (0) | 2023.10.24 |
우커머스 체크아웃에서 '라벨 띄우기'를 할 수 있는 방법이 있습니까?(Shopify처럼) (0) | 2023.10.24 |