简体   繁体   中英

Angular.js $compile doesn`t working

I try to change all input type dates in project to uib-picker-popup, I use directive and $compile but new element doesn`t work. When I put result html to new .html its working fine, I guess there is some problem with $compile.

Source html

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

Directive

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));
        };
      }
    };
  });

Result 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

Thanks for help!

Just wrap it and it works:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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