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

jamiewq
  • 106
  • 1
  • 6
  • The reason why it happened, I think the answer'd not better than this official explanation https://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 http://stackoverflow.com/questions/2051678/getting-all-variables-in-scope – Telvin Nguyen Sep 29 '15 at 03:19

1 Answers1

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);