如何使用 Angularjs 使流式处理更改输入中输入的文本

How to make streaming change the text entered in the input with Angularjs?

本文关键字:输入 文本 处理 Angularjs 何使用      更新时间:2023-09-26

有一个任务来实现文本加密。也就是说,在一个字段中输入要加密的文本,在第二个字段中,按下按钮后,输出密文。但这并不那么有趣,我决定"实时"进行加密。我有必要在第一个字段中只引入一个字符,然后他们在另一个字段中引入了该字符的代码。我知道角度中有ng-model和ng-bind这样的东西,可能需要编写一些函数来处理ng-bind? <textarea ng-bind="model.crypt()"></textarea>

尝试使用过滤器,例如

http://plnkr.co/edit/KuqvWoPy3hGOdXCIxMyQ?p=preview

var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
  $scope.inputText = '';
});
app.filter('cipher', function() {
  return function(input) {
    // Instead of wrapping in <ciphered> it does the cipher transform
    return '<ciphered>' + input + '</ciphered>';
  }
});

模板:

<body ng-controller="MainCtrl">
  <input ng-model="inputText">
  <p>output: {{inputText | cipher }}</p>
</body>

您也可以在控制器上使用一个函数:

app.controller('MainCtrl', function($scope) {
  $scope.inputText = '';
  $scope.toCipher = function(someInput) {
    return '<fn_ciphered>' + someInput + '</fn_ciphered>';
  }
});

和模板:

<body ng-controller="MainCtrl">
  <input ng-model="inputText">
  <p>output using function: <span ng-bind="toCipher(inputText)"></span></p>
</body>

您可以创建一个指令来实现此目的。在输入中必须插入指令:

<input encryp ng-model="model.input">

指令骨架是这样的:

myApp.directive('encryp', function($parse) {
    return {
        restrict: 'EA',
        require: 'ngModel',
        link: function(scope, iElement, iAttrs, controller) {  
          scope.$watch(iAttrs.ngModel, function(value) {
                if (!value) {
                    return;
                }
                //Your encrypter function (if it's in $scope controller)
                var encryp_value = scope.encryp(value);
                controller.$setViewValue(encryp_value);
                controller.$render();
            });
        }
    };
});

你可以在这里找到一个小例子:http://plnkr.co/edit/jL9jKpbETaND2WzcMlg0?p=preview

在此示例中,我的加密函数将每个字符转换为'*'

myApp.controller('MainCtrl', function($scope) {
  $scope.model = {input: ''};
  $scope.encryp = function(someInput) {
    var res = '';
    for(var i = 0; i < someInput.length; i++) {
      res += '*';
    }
    return res;
  }
});