如何使用AngularJS使指令与文本区域一起工作?

时间:2015-10-21 17:26:20

标签: html angularjs angularjs-directive

我有angularJS指令,根据下面的代码工作得很好但在这里我有问题它不让我增加textarea行我不知道为什么它发生我花了几个小时但无法弄清楚问题..我会很感激在这里帮忙......

main.html中

<div class="col-md-7">
    <textarea rows="2" class="form-control"
        ng-model="processDTO.processStatementText"
        id="processStatement" placeholder="Process statement" maxlength="4000"
        chars-ct-tooltip-focus="{{processDTO.processStatementText}}"
        required>
    </textarea>
</div>

directive.js

angular.module('App').directive('charsCtTooltipFocus', function () {  
  'use strict';     
    return{
        restrict: 'A',
        template: '<input tooltip tooltip-placement="top" tooltip-trigger="focus">',
        replace: true,
        link: function (scope, element, attrs) {
              attrs.$observe('charsCtTooltipFocus', function (value) {
              var modelValue = value;
              var maxlength = attrs.maxlength;
              modelValue = maxlength-modelValue.length+' characters left';
              attrs.$set('tooltip', modelValue);
              }); 
        }
    };
});

1 个答案:

答案 0 :(得分:0)

我必须更改指令,因为它被设置为替换true并且仅支持输入字段,因此在我实现的指令下使其在textarea上工作并输入两者。

directive.js

angular.module('riskAssessmentApp').directive('characterCounter', function () {
      'use strict';
        return{
            restrict: 'A',
            require: '^ngModel',
            link: function (scope, element, attrs, ngmodel) {
                var characterCount;
                element.after('<p class="character-count" style="display: none;"><span class="characters-left"></span> characters left</p>');
                element.focus(function(){
                    element.next().show();
                });
                element.focusout(function(){
                    element.next().hide();
                });
                scope.$watch(function(){
                    return ngmodel.$viewValue;
                }, function(newVal, oldVal){
                    if(newVal){
                        characterCount = parseInt(attrs.maxlength - newVal.length, 10);

                    } else{
                        characterCount = parseInt(attrs.maxlength, 10);
                    }
                    element.next().find('.characters-left').text(characterCount);

                })
            }
        };
    });