I have a directive that transcludes some HTML fetched from CMS into my AngularJS app. When I add a script tag into my directive and add a console message to it, the message is being logged twice.
Here's my directive:
angular.module('my-directive', [])
.directive('myDirective', function () {
return {
restrict: 'E',
replace: false,
transclude: true,
template: '<section class="my-directive" ng-transclude>
</section>'
};
});
I am using it like :
<my-directive>
<script>
console.log("ABCD");
</script>
</my-directive>
Expected result: "ABCD" logged once.
Actual result: "ABCD" logged twice.
Can anyone explain why this happens?
Answer is for first time on document.load
the <script>...</script>
run out of your directive it's not depend on your directive at all.
and for 2nd time your directive loaded so you have twice console.
If you want to check use $timeout
to load your template with delay:
open your browser console
return {
restrict: 'E',
replace: false,
transclude: true,
template: '<section ng-transclude ng-if="run"></section>',
link: function (scope) {
$timeout(function () {
scope.run = true
}, 2000)
}
};
How to solve this question?
You don't need script
in the directive! and if you mean customize script for each directive it's another question.
Put your script on link
in your directive:
return {
restrict: 'E',
replace: false,
transclude: true,
template: '<section ng-transclude ng-if="run"></section>',
link: function (scope) {
//----your scripts
console.log("ABCD");
}
};