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.
source share