javascript - 用于更改插入时输入值的 Angular Directive(指令)

标签 javascript html angularjs

我想使用以下自定义指令更改用户输入和模型:

app.directive('changeInput', function ($parse) {
    return {
        require: 'ngModel',
        link: function (scope, elm, attrs, ctrl) {
            //insert logic here
            });
        }
    };
});

因此,任何时候用户都会将字符插入:

<input 
   name="inputText" 
   type="text"
   change-input
   data-ng-model="data.name"
>

例如,输入将从“a”更改为“b”。 我只需要正确的更改逻辑,我尝试使用 $eventpreventDefault() 但它产生了更多问题。

谢谢。

最佳答案

您可以使用 ngModel 的内置解析器和格式化程序 当检测到模型更改时,格式化程序和解析器将触发。用于从模型到 View 的更改的数据格式化程序和用于从 View 到模型的更改的解析器。

app.directive('changeInput', function() {
  return { restrict: 'A',
    require: 'ngModel',
    link: function(scope, element, attrs, ngModel) {
      if(ngModel) { // Don't do anything unless we have a model

        ngModel.$parsers.push(function (value) {
        //value is a
        // 'value' should be your model property
        ngModel.$setValidity('value', true);    
        // sets viewValue

         ngModel.$setViewValue(value); 

        // renders the input with the new viewValue
        ngModel.$render()
        return "b" // you are changing it to b. so now in your controller the value is b and you can trigger your save function
        });

        ngModel.$formatters.push(function (value) {
         //value is b
         return "a" // you are changing it to a. So now in your view it will be changed to a
        });

      }
    }
  };
});

关于javascript - 用于更改插入时输入值的 Angular Directive(指令),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42339667/

相关文章:

javascript - 将 JavaScript 评估到 WKWebView 中以获取视频 URL 不起作用

jquery - 如何让div在下拉菜单中按下另一个div

html - Raphael JS : Cannot mask objects. 替代品?

javascript - 从 AngularJs 调用 Restful api 函数

javascript - 将 Div 置于完全独立的 div 之上

javascript - 为什么这个全局计数器变量不能与 setTimeout 一起使用?

angularjs - 预编译AngularDart模板

angularjs - 测试失败,因为 AngularJS 没有及时初始化

javascript - 导航栏在 Bootstrap 中不起作用 : 4. 0.0-beta.2

java - LibGDX - HTML5 runner,带网络?