如何从指令中听取textarea的变化?

时间:2014-06-30 18:23:53

标签: javascript jquery angularjs

我有一个看起来像这样的textarea:

    <textarea ng-controller="text" autoexpand id="tasks" ng-focus="uncheckAll()" ng-change="processText()" ng-model="tasks.tasks"></textarea>

指令autoexpand根据您编写的行数向textarea添加行。 (它已经在css中设置了nowrap)

//adding rows to the textarea based on the number of newlines.
directive('autoexpand', function($timeout){
    function expand(element){
        var count = element.val().split('\n').length+1;
        element.attr('rows', count)
    }
    return {
        restrict: 'A',
        require: '?ngModel',
        link: function(scope, element){
        //onload
        $timeout(function(){
            expand(element);
        });
        element.on('keydown', function (){
                console.log('change')
                expand(element)
            });
        }

    }
}).

当我通过写入来更新textarea时,这是有效的,但有时候,它会从模型中更新。在这种情况下,如何运行expand()(我尝试了element.on('change'...element.change(element.bind('change',但它似乎根本没有触发

3 个答案:

答案 0 :(得分:1)

您应该以{{1​​}}的方式聆听变更:

ngModel

虽然您当然可以看// here "model" is linked to ng-model property scope.$watch("model", function() { console.log("Changed"); expand(element); }); ,但它会限制您的指令仅用于一个用例。

答案 1 :(得分:0)

您可以通过执行以下操作来聆听模型更改:

scope.$on("ngModel", function(){
    //this will fire when ng model changes
}, true);

答案 2 :(得分:0)

您希望尽可能地听取模型(而不是元素)并做出反应。您可以在指令中使用$watch,只要模型发生更改,它就会触发(无论 如何更改):

scope.$watch(attrs.ngModel, function(){
    expand(element);
});

您甚至不再需要keydown事件处理程序。您需要做的唯一事情是将ng-trim="false"添加到文本区域。否则,模型将忽略空格(包括您键入的任何新行)。

Demo