Angular attribute directive that wraps its element

…衆ロ難τιáo~ 提交于 2019-12-22 12:32:19

问题


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!


回答1:


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

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

Heres a Plunker




回答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" />



回答3:


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.



来源:https://stackoverflow.com/questions/25295882/angular-attribute-directive-that-wraps-its-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!