[英]using angular directve to resize textarea on triggers using element.bind(event, function)
I have a textarea
that I want to resize on certain events using Angular directives. 我有一个
textarea
,我想使用Angular指令在某些事件上调整大小。
What I have so far works for the event 'keydown'
but I can't seem to figure out how to get the functionality working for other events. 到目前为止,我对事件
'keydown'
但似乎无法弄清楚如何使该功能适用于其他事件。
I also tried figuring out how I could possibly achieve this functionality without using jquery's events. 我还尝试了不使用jquery的事件就可以实现此功能的方法。
What I would like is to trigger the update function once the data has been loaded into the textarea and when the entire browser window is resized. 我想要的是一旦将数据加载到文本区域中并且调整整个浏览器窗口的大小时触发更新功能。
Directive: 指示:
var app = angular.module('directives', []);
app.directive('autoGrow', function() {
return function(scope, element, attr){
var update = function(event) {
element.css('height', element[0].scrollHeight + 'px');
}
element.bind('keydown', update); // Works
element.bind('load', update); // Doesn't quite have desired effect.
element.bind('resize', update); // Doesn't quite have desired effect.
update();
}
});
HTML: HTML:
<textarea auto-grow type="text" ng-model="model.foo">
Edit: Just to make sure I got my point across, all the bind elements above trigger as they are supposed to. 编辑:只是为了确保我明白我的意思,上面所有的绑定元素都会按预期触发。 I am just looking for a way that I can trigger my update function when: window is resized and when the ng-model changes or data is updated in the element.
我只是在寻找一种可以在以下情况下触发我的更新功能的方法:调整窗口大小以及元素中ng-model更改或数据更新时。
Here is my proposal: 这是我的建议:
specify that you custom directive requires ng-model directive to be able to watch for modelchanges 指定您的自定义指令需要ng-model指令才能监视模型更改
var app = angular.module('directives', []); var app = angular.module('directives',[]);
app.directive('autoGrow', function($window) { return { require: 'ngModel', link: function(scope, element, attr, ngModelCtrl){ app.directive('autoGrow',function($ window){return {require:'ngModel',link:function(scope,element,attr,ngModelCtrl){
scope.$watch(function () { return ngModelCtrl.$modelValue; }, update, true // if deepwatch is required ); var update = function(event) { element.css('height', element[0].scrollHeight + 'px'); } element.on('keydown', update); // Works element.on('load', update); // Doesn't quite have desired effect. element.on('resize', update); // Doesn't quite have desired effect. update(); angular.element($window).on('resize', update); }
}; };
}); });
More resources: 更多资源:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.