AngularJS - Passing values from backend to frontend

angularjs

Solution

If you need to initialize only a handful of model values from a view the `ng-init` directive might be what you are looking for: http://docs.angularjs.org/api/ng.directive:ngInit

Using it you could simply write:

<div ng-init="myModel=backend-generated-value-here">
   ...
</div>

Having said the above you might have a bit of hard-time finding best practices for your use-case as AngularJS is focused on Web2.0, full-client-side web applications. At the moment it doesn't play ideally with the server-side generate content. It might change in the future versions of AngularJS.

Problem

What's the best way to pass a value from the backend to AngularJS in the frontend? I'm using Django and the templates are able to spit out values that I need, however I'm not sure what's the best practice on passing these values to AngularJS. Think of a blog post and its comments, If I had an AngularJS service that retrieves all the comments of a certain blog post by passing the post ID to the service, and Django is rendering the HTML template and it does know what's the post ID, however I need to pass this post ID to AngularJS and subsequently to the service. One idea is to have it in a hidden `<input>` and assign this input to a model. Not very appealing. Another one is to have a directive and pass this value in an attribute to this directive, this way I would be able to access this attribute's value: ``` // Django (or any backend) is rendering {{ object.value }} <div class="myDirective" data-object-id={{ object.value }}> ... </div> angular.module('myDirectives', []). directive('myDirective', function() { return { restrict: 'C', transclude: false, link: function postLink($scope, $element, $attrs) { // $attrs.objectId would have the value } } }); ``` These two approaches look fine. But I'm wondering if there is a cleaner way of doing this? Any approach that follows AngularJS best practices?

Original source