Reputation: 223
How can I load html from templateURL
in an AngularJS directive in an app built on django.
Whenever I give some URL in the templateURL
variable, it is reaching the django server. How can I implement this? Can I give a django URL in templateURL
variable in directives and render the HTML there in django? What is the proper way of doing this?
My directive:
app.directive('test', function()
{
return{
restrict: 'E',
templateUrl: 'test.html'
}});
It is reaching the django server at someURL/test.html
and returning a 404.
Can i Implement this way?
app.directive('test', function()
{
return{
restrict: 'E',
templateUrl: 'app/test'
}});
and in django urls.py
url(r'^test/$', TemplateView.as_view(template_name='test.html'))
Is this a good way of doing this? What is the proper way?
Upvotes: 4
Views: 2662
Reputation: 648
Sorry to necro but Nobody mentioned
http://www.verdantrefuge.com/writing/2013/angularjs-changing-app-path-base-element/
This completely solved our issue:
<base href="{% static 'js/vendor/myapp/app/' %}" />
<script src="js/Module.js"></script>
and we left templateUrl the same in our directive:
(function () {
'use strict';
angular
.module('site.project.app')
.directive('myDirective', [myDirective])
;
function myDirective() {
return {
restrict: 'E',
replace: true,
controller: 'MyCtrl',
templateUrl: 'partials/my-directive.html',
link: function (scope, elem, attrs) {
}
}
}
})();
Upvotes: 2
Reputation: 5263
Angular runs entirely on the frontend, meaning that any URL you see will be called and treated just like typing the URL in a browser. Taking this into consideration, you need to define the URL in your django project and make sure it responds with what you want to see for your directive.
In short, yes you can do what you proposed: define the URL, make sure it responds in a browser, handle the double curly brackets since it would clash with django's template syntax - use a templatetag
for this, and that's pretty much it.
Upvotes: 0
Reputation: 599778
It depends.
If test.html
is a Django template which needs to be rendered before it gets sent to Angular, then yes this is a good way of doing it.
Otherwise - and I would recommend doing it this way - put your Angular templates in a subdirectory inside your static folder, and reference them via your static URL. Then they'll be served up via exactly the same mechanism as the Angular scripts themselves.
Upvotes: 2
Reputation: 2790
Do one thing:
Crete static folder for your project.
add Static folder to urls.py
then give url in directive as:
templateUrl: 'static/test.html'
Upvotes: 6