Angular: Building a directive and remove attribute from root element

拟墨画扇 提交于 2020-01-25 07:16:11

问题


Is it possible to do something like this:

<field:text id="foo" label="Foo Label" model="model.foo" placeholder="foo" />

which would be compiled to:

<div class="control-group">
   <label class="control-label" for="foo">Foo Label</label>
   <div class="controls">
      <input type="text" id="foo" placeholder="foo" ng-model="model.foo">
   </div>
</div>

I tried to make a example, but Plunker wouldn't let me save my example... uploaded it to dropbox: https://dl.dropbox.com/u/2862814/plunk.zip

The example breaks with stuff like ng-change. This is due the compilation of the ng-change directive. I tried it with a high priority to the fieldText directive, but doesn't fix it.


回答1:


You were pretty close with in your example, but you have to put ng-change on the input-field in the template. Your old code:

<field:text ng-change="updateHidden()" ...

Change this to

<field:text change="updateHidden()" ...

and in the directive (see http://docs.angularjs.org/guide/directive - & or &attr - provides a way to execute an expression in the context of the parent scope.)

{scope:{change:'&' ...

and finally the directive template

<input ng-change="change()" ...

Here is a modiefied and working plunkr: http://plnkr.co/edit/QmQjGQQBRtDmkCka0dul?p=preview

<field:text id="too" label="Too" model="model.too" placeholder="too" change="updateHidden()"></field:text>

<script type="text/ng-template" id="/tpl.html">
<div class="control-group">
   <label class="control-label" for="{{id}}">{{label}}</label>
   <div class="controls">
      <input ng-change="change()" type="text" id="{{id}}" placeholder="{{placeholder}}" 
      ng-model="model">
   </div>
</div>
</script>

directive('fieldText',function(){
  return {
    restrict:'E',
    templateUrl:'/tpl.html',
    scope:{change:'&',id:'@',model:'=',placeholder:'@',label:'@'}
  }
})


来源:https://stackoverflow.com/questions/15919758/angular-building-a-directive-and-remove-attribute-from-root-element

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