When using $ compilation on a component, why does the region go through $ parent?

I am trying to dynamically compile an Angular component using $compile , but the region is not transferred to the component region, but instead to the $ parent region.

Here is a simple component that binds to the myTitle attribute and represents it:

 app.component('myComponent', { bindings: { myTitle: '<' }, template: ` <div> <div>Doesn't work: {{ $ctrl.myTitle}}</div> <div>Works: {{ $parent.$ctrl.myTitle}}</div> </div>` }); 

Then in the controller (or directive, etc.) I will compile it using $ compile:

 app.controller('MainCtrl', function($scope, $element, $compile) { var template = '<my-component></my-component>'; var bindings = { myTitle: 'My Title' } var scope = angular.extend($scope.$new(true), { $ctrl: bindings }); var newElement = $compile(template)(scope); $element.append(newElement); }); 

When performing this result, it gives the result:

Does not work:

Works: My Title

Shows the plunker in action.

Question

Why is the array that I create for a dynamically created component passed as the parent region of the component?

Any pointer to why Angular behaves this way, and perhaps how to avoid it, is greatly appreciated.

+5
source share
1 answer

As I see you need to pass the binding here var template = '<my-component></my-component>';

 var template = '<my-component my-title="$ctrl.myTitle"></my-component>'; 

A full component might be:

 app.controller('MainCtrl', function($scope, $element, $compile) { var template = '<my-component my-title="$ctrl.myTitle"></my-component>'; $scope.$ctrl = {myTitle: 'My Title'}; $element.append($compile(template)($scope)); }); 
+5
source

Source: https://habr.com/ru/post/1268358/


All Articles