2

like the title says, I'm attempting to make an attribute directive that wraps its parent and allows me to toggle between editing and showing the actual model value..

In short:

<input ng-model="model" allow-edit="editing" />

Would end up looking like:

<div>
    <div ng-hide="editing">{{model}}</div>
    <input ng-show="editing" ng-model="model"></input>
</div>

If everything went right.

However, I keep on getting something more along the lines of:

<input ng-model="model">
    <!-- html from allow-edit directive's template --!>
</input>

I've used input as an example here, but I'd like to be able to wrap arbitrary content (select, etc) as well...

Has anyone been able to make a directive that wraps other content on the same element? Is there a better way to do this that I'm not considering?

Thanks for your help!

user3505342
  • 76
  • 1
  • 6

3 Answers3

2

I hope this answers your question:
In directive options:

  1. set replace: true
  2. set transclude: "element"
  3. use ng-transclude where ever you want to put the original element within the wrapper template.

plunker link

example:

js:

var app = angular.module("test", []);

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

HTML:

<input my-custom-input type="text" />
Community
  • 1
  • 1
Alireza Mirian
  • 5,862
  • 3
  • 29
  • 48
  • While this solution nicely wraps the original input element without modifying it, there is no toggling going on here, which is what the question was about. – Phil Degenhardt Oct 13 '15 at 21:58
  • While it wraps the HTML as asked, for some reasons attributes like `ng-model` are broken with this method and do not work anymore on the wrapped input. – Seb D. Aug 11 '16 at 08:53
1

What you want to do is replace:true but maintain "=ngModel"

replace:true,
scope:{
  mymodel:"=ngModel",
  editing:"=allowEdit"
}

Heres a Plunker

Dylan
  • 4,703
  • 1
  • 20
  • 23
  • It should be noted that any other attributes you apply to the input element will be lost -- they are migrated to the wrapper element. So this addresses the specific example in the question, it has serious limitations. – Phil Degenhardt Oct 13 '15 at 21:51
0

I think that using replace : true should enable you to replace the original content. Take a look at this StackOverflow answer: Here

If you had a bit more of your directive, I could have a go at getting it to work, but hopefully you can use the plnkr of the other answer to work it out.

Community
  • 1
  • 1
Caspar Harmer
  • 8,097
  • 2
  • 42
  • 39
  • Thanks for the response! I wouldn't like to actually replace the original content though... Instead, I'd like to insert the original content into my directive template. – user3505342 Aug 13 '14 at 21:27