databinding custom directive angular with replacing html in compile function

做~自己de王妃 提交于 2019-12-25 01:01:48

问题


i am trying to write a directive that replaces an input field with an custom made input field. However, I can not get the databinding to work as the model does not show in the directive input field.

I have created a jsFiddle here:

http://jsfiddle.net/6HcGS/392/

I guess i dont really know what to place here for the databinding to work:

tElement.replaceWith('<input ng-model="ngModel" type="text" />');

If anybody could help me out i would be very grateful as this has been a problem for me for a whole day now.

Cheers!


回答1:


tElement.replaceWith('<input ng-model="ngModel" type="text" />');

Angularjs doesn't know that ngModel is a binding. It's interpreted as a simple string. So you need to tell angular this. I've updated your jsfiddle to show you how to do this: http://jsfiddle.net/6HcGS/393/

But you can do it even simpler by removing the isolated scope in the directive: http://jsfiddle.net/6HcGS/394/.

Like lort already mentioned the attributes are getting passed to the element during replacement. Of course only if you dont use isolated scope.




回答2:


I don't understand what you're trying to do but it seems that following code example is all you need:

angular.module('zippyModule', [])
.directive('zippy', function(){
    return {
      restrict: 'C',
      replace: true,
      template: '<textarea></textarea>',
    }
});

This one changes initial input into textarea. Binding through ng-model still works because other attributes are not deleted from element during replacement.



来源:https://stackoverflow.com/questions/19597068/databinding-custom-directive-angular-with-replacing-html-in-compile-function

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