How to pass a data object to a dynamically created

2019-08-12 05:22发布

问题:

What I want to do is pretty simple, here is a fiddle to illustrate what I would like to achieve: code here: http://jsfiddle.net/vxpc1dry/

Basically on data fetch success I want to pass the returned response data object to a dynamically compiled directive, only the data object seems to be undefined not matter what :(

Any idea what I'm doing wrong? thanks a lot!

回答1:

angular.element(document.getElementById('dirContainer')).append($compile("<my-dynamic-directive name='data.name' data='data'></my-dynamic-directive>")(scope));

use two way = or one way & binding instead of text @ binding

myApp.directive("myDynamicDirective", function () {
    return {
        restrict: "E",
        scope: {
            data: "=",
            name: "="
        },
        template: "<div class='dynadir'><div>hello {{name}} <-- OK</div>"+
        "<div>hello {{data.name}} <-- WTF?</div></div>",    // <- undefined why?
        link: function (scope, element, attr) {
            console.log("The data passed: %O", scope.data); // <- undefined why?
        }
    }
});

http://jsfiddle.net/vxpc1dry/7/