Angular编译输入与非编译输入的工作方式不同

时间:2016-02-02 11:09:07

标签: javascript angularjs

我正在尝试使用angular指令动态创建输入,这样做时我遇到了一些奇怪的事情。我已经将我所做的事情简化为一个简单的plunk

的index.html

<body ng-controller="mainController as vm">
  <h1>{{vm.title}}</h1>

  <input type="text" ng-model="vm.title" pu-elastic-input />
  <a-input this-is-for="title" />
</body>

的script.js

(function() {
  angular
  .module('app', ['puElasticInput'])
  .controller('mainController', function mainController() {
    var vm = this;

    this.title = 'hello world!';
  })
  .directive('aInput', function($compile) {
    return {
      restrict: 'E',
      link: function (scope, element, attributes) {
        var input = angular.element('<input />');

        input.attr('type', 'text');
        input.attr('ng-model', 'vm.' + attributes['thisIsFor']);
        input.attr('pu-elastic-input', '');

        element.replaceWith($compile(input)(scope));
      },
    }
  });
}());

基本上这两个输入应该是相同的大小,但是编译的(右)大于左边的输入。我使用角弹性输入进行动态调整。我注意到其他一些做类似事情的东西,但这些都是插件的一部分。

1 个答案:

答案 0 :(得分:1)

Here's a forked plunkr that works,我已更改了您的$compile功能,因此它使用了克隆节点。

$compile(input)(scope, function(clone) {
    element.replaceWith(clone);
});
  

cloneAttachFn - 如果提供了cloneAttachFn,则链接函数将克隆模板并调用cloneAttachFn函数,允许调用者将克隆元素附加到适当位置的DOM文档。 cloneAttachFn被称为:   cloneAttachFn(clonedElement,scope)

相关问题