AngularJS <script> Directive



  • AngularJS alters the default behaviors of the <script> element.
  • The content of the <script> element is a loaded with $templatecache, which means the template can be used by ngView, ngInclude or directives.
  • The script element type is defined as text/ng-template.
  • A template cache name must be assigned through the elements id which is used as directives by templateUrl.
  • This directive executes at priority level 0.

Syntax for script directive in AngularJS:

<script type="string" 
        id="string">
</script>

Parameter Values:

Parameters Type Description
type string It specifies the type must be set to ‘text/ng-template’.
id string Denotes the cache name of the template.

Sample coding for script directive in AngularJS:

 Tryit<!DOCTYPE html>
<html>
    <head>
        <title>Wikitechy AngularJS Tutorials</title>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/
                    angular.min.js"> </script>
    </head>
    <body ng-app="">
        <script type="text/ng-template" id="tempfile">Content in the script 
        directive</script>
        <a ng-click="currenttemp='tempfile'" id="temp-link">Click here to view 
        content</a>
        <div id="temp-content" ng-include src="currenttemp"></div>
    </body>
</html>

Using script directive in AngularJS:

<script type="text/ng-template" id="tempfile">Content in the script directive</script>

Code Explanation for script directive in AngularJS:

Code Explanation for AngularJS script Directive

  1. The ng-app specifies the root element (e.g. <body> or <html> or <div> tags) to define AngularJS application.
  2. script tag defined with the type “text/ng-template”
  3. id=tempfile is the id of the script directive
  4. currenttemp is the file name of the element.
  5. temp-link is given for the current template link
  6. temp-content is the id of the element which is used to get the source from the currenttemp.
  7. nginclude directive is used to include the file of the “currenttemp”.

Sample Output for script directive in AngularJS:

Sample Output for AngularJS script Directive

  1. The current content is displayed in the output on page load.
Sample Output for AngularJS script Directive

  1. If the user click the end of the current content.
  2. The next template is displayed in the output.

Related Searches to angularjs create directive