【问题标题】:Add prefix value to input filed in AngularJS向AngularJS中的输入字段添加前缀值
【发布时间】:2015-12-16 17:49:37
【问题描述】:

我有这样的需求。

<label>Website Address</label>
                    <span><input type="text" class="form-factor" data-ng-model="websiteUrl"/></span>

我有这样的 HTML 代码。一旦用户在网站 URL 字段中输入文本,我需要使用 http:// 为 URL 添加前缀。

如果用户输入带有http:// 的URL。则无需添加http:// 前缀。

我如何在 AngularJS 中使用。

请推荐

【问题讨论】:

  • 模型应该包含 http:// 还是只包含您的输出?
  • 尝试使用或创建一个过滤器来处理所有正则表达式检查并根据需要返回 url
  • 无论何时获得输出文本,您都可以轻松追加知道吗?

标签: javascript angularjs angularjs-directive


【解决方案1】:

好的,还有另一种可能使用格式化程序和解析器来完成模型级别的任务。我将代码从另一个解决方案放在这里,因为那里的代码托管在外部:

https://stackoverflow.com/a/19482887/3641016

angular.module('app', [])
  .controller('testCtrl', function($scope) {
    $scope.input1 = "";
    $scope.input2 = "";
  })
  .filter('prefixHttp', function() {
    return function(input) {
      return input.indexOf("http://") == 0 ? input : 'http://' + input;
    };
  })
  .directive('httpPrefix', function() {
    return {
      restrict: 'A',
      require: 'ngModel',
      link: function(scope, element, attrs, controller) {
        function ensureHttpPrefix(value) {
          // Need to add prefix if we don't have http:// prefix already AND we don't have part of it
          if (value && !/^(https?):\/\//i.test(value) && 'http://'.indexOf(value) !== 0 && 'https://'.indexOf(value) !== 0) {
            controller.$setViewValue('http://' + value);
            controller.$render();
            return 'http://' + value;
          } else
            return value;
        }
        controller.$formatters.push(ensureHttpPrefix);
        controller.$parsers.splice(0, 0, ensureHttpPrefix);
      }
    };
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<div ng-app="app" ng-controller="testCtrl">
  <label>prefix the output
    <input ng-model="input1" />{{input1 | prefixHttp}}
  </label>
  <br/>

  <label>prefix the model
    <input ng-model="input2" http-prefix/>{{input2}}
  </label>
</div>

【讨论】:

  • 感谢您的回复。在我的情况下,当用户开始输入输入字段时,我需要将 http:// 添加到输入字段。有可能吗??
  • @Kichu 有这种可能性。看看改进后的答案
猜你喜欢
  • 2013-10-29
  • 1970-01-01
  • 2019-11-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-15
  • 1970-01-01
相关资源
最近更新 更多