use $templateCache via script tag

249 views Asked by At

I will use the $templateCache script tag to show my html view. Currently I have ,

<body ng-app="myApp">
    <div ng-controller="myAppController">
    ....
    ....
    <div class="col-xs-12">
        <my-settings></my-settings>
    </div>

..
..
    </div>

And my app.js,

var myApp = angular.module('myApp', ['editor']);

myApp.config(['$httpProvider', function($httpProvider) {
 ....
 ....
}]);

myApp.controller('myAppController', ['$scope', '$http', '$rootScope', function ($scope, $http,$rootScope) {
//Other stuff
}

directive.js

'use strict';

angular.module('editor').directive("my-settings", function() {
    return {
        templateUrl: '/views/templateId.html'
    };
});

I want to use $templateCache via the script tag or as a service.But while adding this via service, I have to put all my html element in $templateCache.put().

var myApp = angular.module('myApp', []);
myApp.run(function($templateCache) {
  $templateCache.put('templateId.html', 'This is the content of the template');
});

Now I think, I will use the script tag instead.

<script type="text/ng-template" id="templateId.html">
  <p>This is the content of the template</p>
</script>

From the documentation, it must be a descendent of the $rootElement. So where I have to place the script.Will this be included inside <body ng-app="myApp"> in the same file itself?

1

There are 1 answers

3
31piy On

You need to use camel casing while defining the name for the directive:

.directive("mySettings" ...

Also, you can define the inline template in the same scope as of the directive, like this:

<div ng-controller="myAppController">
    ....
    ....
    <div class="col-xs-12">
        <my-settings></my-settings>
    </div>

..
..
    <script type="text/ng-template" id="templateId.html">
      <p>This is the content of the template</p>
    </script>
  </div>

Just ensure that the ID of inline template matches the templateUrl. You can check out a working fiddle here.