简体   繁体   中英

Move HTML content and retain AngularJS two-way data binding

There's something I'm not getting about Angular. I have an AngularJS page where I have to move around content but have data binding on it. I have a fiddle here that illustrates what I want to do, and the problem: 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. 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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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