Angular指令用于更改insert上的输入值

时间:2017-02-20 08:28:59

标签: javascript html angularjs

我想使用cutom指令更改用户输入和模型,如:

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

因此,只要用户在以下位置插入char:

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

输入将改变为&#39; a&#39;到&#39;&#39;例如。 我只需要正确的改变逻辑,我尝试使用$eventpreventDefault(),但它创造了更多的问题。

感谢。

1 个答案:

答案 0 :(得分:1)

您可以在ngModel的解析器和格式化程序中使用内置版本 检测到模型更改时,格式化程序和解析器将触发。格式化,用于从模型更改为视图和解析器的数据,以便从视图更改为模型。

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
        });

      }
    }
  };
});
相关问题