简体   繁体   English

如何使用角度指令包装元素?

[英]How to wrap an element using an angular directive?

I'm trying to create an angular component that adds a prefix to an <input> element. 我正在尝试创建一个向<input>元素添加前缀的角度组件。 Something like this: 像这样:

前缀/后缀

The idea would be to use it like this: 想法是像这样使用它:

<input type="text name="url" input-prefix="http://">

For this I need to wrap the <input> around a <div> container which will also include a <span> with the prefix and add some custom CSS. 为此,我需要将<input>包裹在<input> <div>容器周围,该容器还将包含带有前缀的<span>并添加一些自定义CSS。

I believe I need to use the directive compile function to achieve this because of the DOM manipulation, but I don't understand very well how it works and I haven't found much documentation. 我相信由于DOM操作,我需要使用指令compile功能来实现此目的,但是我不太了解它是如何工作的,并且我也没有找到太多文档。

The issue I found so far is that after manipulating the DOM on the compile function, the <input> appears to be completely unusable, I cannot even type in it. 到目前为止,我发现的问题是,在编译函数上操作了DOM之后, <input>似乎完全不可用,我什至无法键入它。 Here's my fiddle: 这是我的小提琴:

http://codepen.io/anon/pen/vokxy - Can't type on the <input> inside the green wrapper. http://codepen.io/anon/pen/vokxy-无法在绿色包装纸内的<input>上键入。

You don't manipulate the DOM in the compile phase, you do it in link phase (postLink actually), since the DOM isn't actually set up correctly until then. 您没有在编译阶段就操作DOM,而是在链接阶段(实际上是postLink)进行操作,因为在那之前DOM尚未真正正确设置。 There's an example in the Developer Guide . 开发人员指南中有一个示例。

Moved your code to link method, here's a working example. 将代码移至链接方法,这是一个有效的示例。

Example: 例:

var app = angular.module('my-app', []);

app.controller("myController", function($scope) {
  $scope.ctrl = this;
  $scope.name = "w";
  $scope.minLength = 3;
});

    app.directive("inputPrefix", function() {
      return {
        restrict: 'A',
        link: function(scope,element, attrs) {
          var wrapper = angular.element(
            '<div class="prefixed-input">');

          element.after(wrapper);           
          element.removeAttr("input-prefix");
          wrapper.append(element);                     
        }
      }
    });

Live example: http://jsfiddle.net/choroshin/cnc5m/ 实时示例: http//jsfiddle.net/choroshin/cnc5m/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM