gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:14:49 25 4
gpt4 key购买 nike

我有这样的需求。

<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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com