Angular.js $ compile没有工作

时间:2016-02-19 14:06:33

标签: javascript angularjs angularjs-directive datepicker angularjs-bootstrap

我尝试将项目中的所有输入类型日期更改为uib-picker-popup,我使用指令和$ compile但新元素不起作用。当我把结果html放到新的.html它工作正常时,我想$ compile有一些问题。

来源html

<input type="date" ng-model="picker" />

指令

angular.module('ui.bootstrap.demo').directive('input', function ($compile) {
    return {
      require: 'ngModel',
      compile: function (tElem, tAttr) {
        if (tAttr.type !== 'date') {
          return;
        }

        return function (scope, elm, attrs, ngModelCtrl) {
            var ngModel   = elm.attr('ng-model');
            var name      = elm.attr('name');
            var className = elm.attr('class');
            var newElement = '<input type="text" class="' + className + '" ng-model="' + ngModel + '" name="' + name + '" uib-datepicker-popup is-open="isOpen">' +
                '<button type="button" class="btn btn-primary" ng-click="isOpen = true">+</button>';
            elm.replaceWith($compile(newElement)(scope));
        };
      }
    };
  });

结果html

<input type="text" class="ng-pristine ng-valid ng-scope ng-isolate-scope ng-valid-date ng-touched" ng-model="picker" name="undefined" uib-datepicker-popup="" is-open="isOpen" style="">

<button type="button" class="btn btn-primary ng-scope" ng-click="isOpen = true">+</button>

plunker here

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

只需将其包裹起来就可以了:

var newElement = '<div><input type="text" class="' + className + '" ng-model="' + ngModel + '" name="' + name + '" uib-datepicker-popup is-open="isOpen">' +
                '<button type="button" class="btn btn-primary" ng-click="isOpen = true">+</button></div>';
elm.replaceWith($compile(newElement)(scope));

http://plnkr.co/edit/JPSpVyWgDJeC0NtNhnib?p=preview