问题
Does AngularJS have equivalent to this:
elementObject.addEventListener("resize", myFunction);
I thought about about watches, but I don't think it's the good solution.
回答1:
Create a custom directive:
app.directive("myResize", function($parse) {
return {
link: postLink
};
function postLink(scope, elem, attrs) {
elem.on("resize", function (e) {
var rs = $parse(attrs.myResize);
rs(scope, {$event: e});
scope.$apply();
});
}
});
Usage:
<div my-resize="$ctrl.myFunction($event)">
</div>
For more information,
- AngularJS Developer Guide - Creating Custom Directives
- AngularJS Comprehensive Directive API Reference
- AngularJS $parse Service API Reference
- AngularJS jqLite API Reference
回答2:
You can also do this: HTML:
<div resize-me></div>
JavaScript:
myApp.directive('resizeMe', ['$window', function($window) {
return {
link: function(scope, elem, attrs) {
angular.element(elem).bind('resize', function() {
//do something on resize
})
}
}
}])
来源:https://stackoverflow.com/questions/45039891/angularjs-element-onresize-event-custom-directive