如何在Angular 1.x中对输入字段使用自定义指令
How to use custom directive on Input fields in Angular 1.x?
我试图使用自定义AngularJS指令修改input
元素。基本上,我想用国家下拉列表替换任何<input type="country">
字段。
但该指令似乎不与input
字段工作。如果我把它改成其他标签,它能工作吗?
代码如下:
angular.module('plunker', [])
.controller('MainCtrl', function ($scope) {
$scope.name = 'World';
});
angular.module('plunker')
.directive('input', function() {
return {
restrict: 'E',
scope: {ngModel: '=?'},
link: function(scope, elem, attr) {
if(attr.type === 'country') {
elem.html('html code for select');
alert(elem);
}
}
};
});
<!doctype html>
<html ng-app="plunker" >
<head>
<meta charset="utf-8">
<title>AngularJS Plunker</title>
<link rel="stylesheet" href="style.css">
<script>document.write("<base href='"" + document.location + "'" />");</script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
Name: <input type="country" ng-model="name"/> <br/>
</body>
</html>
有人可以解释和建议一个解决方法?
注:我也试过在指令中这样做,但它也不起作用!
replace: true,
template:'<div>hello</div>'
注:我知道我可以使用ng-country
或其他自定义标签,但我想改变input
标签只是因为我想知道为什么会发生这种情况,或者可能找出我做错了什么?
最新更新:
你的代码只是在元素上设置html,而不是替换它。您可能希望像这样使用replaceWith:var app = angular.module("TestApp",[]);
app.controller("TestController", function($scope){
$scope.message = "Input Directive Test"
});
app.directive("input", function() {
return {
restrict: "E",
link: function(scope, elem, attr) {
if(attr.type === "country") {
var select = angular.element("<select><option>USA</option></select>");
elem.replaceWith(select);
}
}
}
});
这里是JSBin: https://jsbin.com/juxici/4/edit?html,js,output
我的答案的初始版本:
这里有一个例子,当使用'replace'和'template'时没有任何问题。我不检查类型之类的,但你可以在链接器代码中这样做。
JSBin: https://jsbin.com/juxici/2/edit?html、js、输出
HTML<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js"></script>
</head>
<body ng-app="TestApp">
<div ng-controller="TestController">
<h2>{{message}}</h2>
<input type="country" ng-model="name"/>
</div>
</body>
</html>
Javascript: var app = angular.module("TestApp",[]);
app.controller("TestController", function($scope){
$scope.message = "Input Directive Test"
});
app.directive("input", function() {
return {
restrict: "E",
replace: true,
template:"<select><option>USA</option></select>"
}
});
相关文章:
- 将输入字段中的文本提交到我的数据库,同时将其添加到我的列表中
- 而循环只设置php中输入字段中的第一个值
- 使用 Javascript 将字段输入除以 12
- 合并来自多个字段输入的搜索结果
- 使用 Javascript 实时打印字段输入数据
- 防止AngularJS中跨路由的字段输入重复
- 引用Iframe中的字段输入
- 禁用html5”;“必需”;不显示窗体部分时的字段输入属性
- JavaScriptFormValidation-需要特定的字段输入,但使用大写/小写
- 验证VF页面上所需字段输入的Javascript不起作用
- 在没有
- 使用Jquery将字段输入值作为查询字符串附加到url
- HTML5 jQuery选择所有日期字段'输入:date'
- 将字段输入复制到另一个字段输入
- 向图像添加字段(输入)
- 动态添加字段输入不会存储值并传递给控制器
- 向输入字段输入键击
- 我如何通过javascript验证datetime字段输入
- HTML如何将用户字段输入作为json对象发送
- 如何根据'select' onchange事件将值填充到第二个输入字段?输入