首页 > 解决方案 > 特殊字符不会从输入表单中显示在 AngularJS 中,例如 % & ? @

问题描述

我有一个 AngularJS 表单,它在输入框下方的代码片段中显示来自输入框的密码。但是当用户在密码中输入任何特殊字符时,密码将不再显示,甚至非特殊字符也不会显示。Chrome、Firefox 和 Internet Explorer 的结果相同。

表单脚本:

<script>
    angular.module('tutorialApp', [])
        .controller('TutorialController', ['$scope', function($scope) {
            $scope.tutorial = {
                ipno: '123.456.7.8',
                sudouser: 'mysudouser1',
                dbname: 'mydb1',
                dbuser: 'mydbuser1',
                dbpw: 'mydbpassword',
                yourdomain: 'yourdomain.com',
                your2nddomain: 'test.yourdomain.com',
                name: 'name',
                word: /^\s*\w*\s*$/
            };
        }]);
</script>

表单输入:

<label for="dbpw">Database password:</label>
        <input type="text" name="dbpw" ng-model="tutorial.dbpw" ng-pattern="tutorial.word" id="dbpw">

代码片段:

<code>CREATE USER '<span class="frominput">{{tutorial.dbuser}}</span>'@'localhost' IDENTIFIED BY '<span class="frominput">{{tutorial.dbpw}}</span>';</code>

标签: angularjsdata-bindingspecial-characters

解决方案


您需要添加allowInvalid. ng-model-options添加这个input-ng-model-options="{ allowInvalid: true }"检查这个 - https://docs.angularjs.org/api/ng/directive/ngModelOptions

angular.module('tutorialApp', [])
        .controller('TutorialController', ['$scope', function($scope) {
            $scope.tutorial = {
                ipno: '123.456.7.8',
                sudouser: 'mysudouser1',
                dbname: 'mydb1',
                dbuser: 'mydbuser1',
                dbpw: 'mydbpassword',
                yourdomain: 'yourdomain.com',
                your2nddomain: 'test.yourdomain.com',
                name: 'name',
                word: /^\s*\w*\s*$/
            };
        }]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>


<div ng-app="tutorialApp" ng-controller="TutorialController">
  <label for="dbpw">Database password:</label>
    <input type="text" name="dbpw" ng-model="tutorial.dbpw" ng-pattern="tutorial.word" id="dbpw" ng-model-options="{ allowInvalid: true}">

  <br><br>
  
  <code>CREATE USER '<span class="frominput">{{tutorial.dbuser}}</span>'@'localhost' IDENTIFIED BY '<span class="frominput">{{tutorial.dbpw}}</span>';</code>
</div>


推荐阅读