I’m working on a web application where I need to send data from my Django backend to the AngularJS frontend. The Django templates can output the values I need, but I’m not sure about the best approach to get these values into AngularJS.
Here’s my situation: I have a news article page with user comments. My AngularJS service fetches comments for a specific article using the article ID. Django renders the template and knows the article ID, but I need to make this ID available to AngularJS so it can call the service properly.
I’ve tried a couple of methods. First option is using a hidden form field and binding it to a model, but this feels messy.
Second approach uses a custom directive with the value passed as an attribute:
// Django renders {{ article.id }}
<div class="articleComments" data-article-id={{ article.id }}>
...
</div>
angular.module('articleApp', [])
.directive('articleComments', function() {
return {
restrict: 'C',
transclude: false,
link: function setupLink($scope, $element, $attrs) {
// $attrs.articleId contains the needed value
var articleId = $attrs.articleId;
}
};
});
Both methods work, but I’m wondering if there’s a more elegant solution that follows AngularJS conventions better. What would be the recommended way to handle this data transfer?