0

I am doing something like this in Angular.
After compiled, the object will not be passed to the DirectiveB correctly.
However, if I passed the object defined in scope, it will be fine.
I wonder why this happens and how can I pass an object(not in scope) to a directive with a compiled html string in an easy way? I used closure to do that, but it is not easy to maintain.

In DirectiveA.js:

.directive('DirectiveA', function($compile, $parse) {
    return
    ...
    link: function(scope, element, attrs) {

        function func_be_called_somewhere (...) {

            var obj= {"key":"value"};   //obj is not in scope, I create it here

            var el = '<DirectiveB para="obj" ...>';
            var content = $compile(el)(scope);  //compiled here
            element.append(content);
        }
    }
}


In DirectiveB.js:

.directive('DirectiveB', function($compile, $rootScope, $parse) {
    ...
    scope: {
        ...
        para: '='
        ...
    }
    link: function(scope, element, attr) {
        console.log(scope.para); //undefined
    }
}

JS BIN : http://jsbin.com/depohoqofi/edit?html,js,console,output

1
  • The reason why it happened, I think the answer'd not better than this official explanation docs.angularjs.org/api/ng/service/$compile. "Compiles an HTML string or DOM into a template and produces a template function, which can then be used to link scope and the template together.". Merging or rewriting some existent code into the directive and move the essential variables into the scope is the pain for your case now, but clearly you have to do that. The problem is quite related to stackoverflow.com/questions/2051678/… Commented Sep 29, 2015 at 3:19

1 Answer 1

0

I think you should put your obj in your scope :

scope.obj= {"key":"value"};   //obj is not in scope, I create it here
var el = '<DirectiveB para="scope.obj" ...>';
var content = $compile(el)(scope);  //compiled here
element.append(content);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.