简体   繁体   English

移动HTML内容并保留AngularJS双向数据绑定

[英]Move HTML content and retain AngularJS two-way data binding

There's something I'm not getting about Angular. 我对Angular不太了解。 I have an AngularJS page where I have to move around content but have data binding on it. 我有一个AngularJS页面,我必须在其中移动内容,但要在上面绑定数据。 I have a fiddle here that illustrates what I want to do, and the problem: http://jsfiddle.net/gbisaga/cmzBL/6/ 我在这里有一个小提琴,用来说明我想做的事和问题: http : //jsfiddle.net/gbisaga/cmzBL/6/

<input type="text" size="50" ng-model="model.dentist" name="petDentist" />

If you change the "name" or "type" fields, the displayed string value below changes; 如果更改“名称”或“类型”字段,则下面显示的字符串值会更改; but if you change the doggy dentist field, it does not. 但是如果您更改狗牙医字段,则不会。 When I move the content over I want this element to continue to be bound to the model; 当我将内容移到上方时,我希望此元素继续与模型绑定; as you can see in the fiddle, it's not. 正如您在小提琴中看到的那样,事实并非如此。

I'm guessing what's actually happening is the field's value is filled in BEFORE my-append-children is executed, and the binding is never actually taking place. 我猜测实际发生的是在执行my-append-children之前,字段的值已被填充,并且绑定从未真正进行过。 I have also played with changing to a compile function rather than a link in my directive, but that works even less well. 我还玩过更改为编译功能而不是指令中的链接的方法,但是效果不佳。 There's something I'm clearly not getting here. 我显然没有到达这里。

You need to add this at the end of your directive: 您需要在指令末尾添加此代码:

$compile(target.contents())(scope);

The updated fiddle: Fiddle 更新的小提琴: 小提琴

You need to compile the markup that was added so angular can interpret it. 您需要编译添加的标记,以便angular可以解释它。

You need to remove the element after you move the children to the target. 将子级移动到目标后,需要删除该元素。 If you do element.remove() it will also remove all the bindings and eventhandlers on that element and its children 如果执行element.remove(),还将删除该元素及其子元素上的所有绑定和事件处理程序

    .directive('myAppendChildren', function() {
    return {
        restrict: 'E',
        link: function (scope, element, attrs) {
            var target = $(attrs.target);
            target.append(element.children());
            element.remove();
        }
    };
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM