2017-02-20 52 views
0

输入值我想用一对自定义指令等,以改变用户输入和模型:角指令来改变插入

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(),但它创造了更多的问题。

谢谢。

+0

它不清楚你问什么。如果输入从“a”变为“b”,会发生什么? – lin

+0

如何使用指令将用户输入从a更改为b。 –

+0

用户插入a但b会出现。 –

回答

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

     } 
    } 
    }; 
}); 
+0

太好了,但是如果我想改变字符串输入。 –

+0

@ItsikMauyhas我更新了我的答案,如果你需要更具体的东西请给我提供更多信息 –

+1

工程很好,谢谢。 –