如何在Angular 1.x中对输入字段使用自定义指令

How to use custom directive on Input fields in Angular 1.x?

本文关键字:字段 输入 指令 自定义 Angular      更新时间:2023-09-26

我试图使用自定义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>"
  }
});