javascript - 向 AngularJS 中的输入字段添加前缀值

标签 javascript angularjs angularjs-directive

我有这样的需求。

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

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

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

我如何在 AngularJS 中使用。

请推荐

最佳答案

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

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>

关于javascript - 向 AngularJS 中的输入字段添加前缀值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34307576/

相关文章:

javascript - jquery keyup() 延迟不起作用

javascript - 为什么 Visual Studio 的 AngularJS 模板嵌入到函数调用中?

javascript - 将焦点设置在输入上的指令不起作用

javascript - AES 加密 PHP 到 NodeJS?

javascript - 使用 javascript 替换插入 <span> 标签

javascript - 有没有办法有条件地将数据从 `ng-repeat` 传递到其他元素?

angularjs - 我如何以 Angular 动态显示我的 Flash 消息。消息必须来自 API 响应

javascript - 当我使用 angularjs 配置时,页面重定向到 IE8 中的主页

javascript - Google map 不在选项卡上显示 map

javascript - 访问 ng-repeat 的项目范围