Search code examples
javascriptangularjsangularjs-directiveangular-ngmodeltransclusion

AngularJS : Wrapping an element into a custom template with an angular attribute directive


Situation:

I have an attribute directive that wraps it's element into a template. Here it is:

app.directive("myCustomInput", function(){
  return{
    restrict: "A",
    replace: true,
    scope:{},
    transclude: "element",
    template: "<div class='input-wrap'>"+
    "<div ng-transclude></div>"+
    "<i class='glyphicon glyphicon-chevron-down'></i>"+
    "</div>"
  }
});

And I use it like:

<input my-custom-input ng-model="data.input" type="text" />

Problem:

ng-model doesn't work

Here is the plunker


Solution

  • You may have encountered a possibly bug. It is a priority and directive processing order issue. Set your directive higher priority than the ng-model. When using 1.2 v, ng-model has the default priority of 0 and with 1.3 version ng-model has a priority 1. So let your directive have a higher priority than the ng-model so that the directive and transclusion happens before ng-model processes the input before your directive renders.

    .directive("myCustomInput", function(){
      return{
        restrict: "A",
        replace: true,
        scope:{},
        priority: 1, //Here set the priority
        transclude: "element",
        template: "<div class='input-wrap'>"+
        "<div ng-transclude></div>"+
        "<i class='glyphicon glyphicon-chevron-down'></i>"+
        "</div>"
      }
    });
    

    Demo