How does the Angular compile () function allow access to an isolated area?

I have the following directive:

angular.module("example_module", []) .directive("mydirective", function() { return { scope: { data: "@mydirective" } compile: function(element) { element.html('{{example}}'); return function($scope) { $scope.example = $scope.data + "!"; }; } }; }); 

and the following HTML code:

 <!DOCTYPE html> <html ng-app="example_module"> <head> <meta charset="utf-8"> <title>Example title</title> <script src="lib/angular/angular.min.js"></script> <script src="js/example.js"></script> </head> <body> <div mydirective="Hello world"></div> </body> </html> 

I would expect the directive to compile in Hello world! but instead compiles to an empty string. scope creates an isolated scope that is inaccessible to {{example}} .

I would like to know how the new HTML generated by compile() can access the link $scope function.

+5
source share
1 answer

This does not work because {{example}} is evaluated against the parent scope, which makes sense since you essentially change the element before compiling to:

 <div>{{example}}<div> 

You can check by replacing '$ scope.example =' with $ scope. $ parent.example = '(for demo purposes only, this is not the best practice of using $ parent).

What you're actually trying to do is like switching, but there are very simple ways to do this. For instance:

 angular.module("example_module", []) .directive("mydirective", function() { return { restrict: 'A', scope: { data: "@mydirective" }, template: '{{example}}', compile: function(element) { return function($scope) { console.log($scope.data); $scope.example = $scope.data + "!"; console.log($scope.example); }; } }; }); 

When using a template, it replaces the contents of the element to which the directive applies (if you do not use replace: true, in which case it replaces the entire element), and the contents of the template are evaluated using the scope directive.

You can do what you are trying to do using the transclude parameter passed for compilation ( see the docs ), but this is deprecated, so I would not recommend going down this road.

Here is Plunk where you can play with some options.

+4
source

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


All Articles