Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS: Initialize model from data in HTML?

I'm thinking about trying to initialize (parts of) the AngularJS model from data in the HTML, rather than doing a request to the server to fetch the data as JSON, or embed a JSON object directly in the page.

(The server currently only renders the data in HTML (not JSON), and I'd like to avoid rewriting "too much" code right now, and HTML works well with search engines. The application itself is a discussion system.)

Here follows an example of my HTML (simplified). The data embedded therein is a post ID (123456), an author ID (789), an author name (Kitty overlord) and a text message ("Kittens Cats! Just kidding.").

<div id="post-123456">
  <div class="dw-p-hd">
    By <span data-dw-u-id="789">Kitty overlord</span>
  </div>
  <div class="dw-p-bd">
    <p>Kittens</p><p><strike>Cats! Just kidding.</strike></p>
  </div>
</div>

And I'd like to construct an AngularJS controller, and initialize $scope to something like:

$scope = {
  postId = 123456,
  authorId = 789,
  text = 'Kittens ....',
}

Perhaps I can use ng-init like so:

<div id="post-123456"
     ng-controller="CommentCtrl"
     ng-init="{ postId =..., authorId =..., text =... }">      <--- look here
  <div class="dw-p-hd">
    By <span data-dw-u-id="789">Kitty overlord</span>
  </div>
  <div class="dw-p-bd">
    <p>Kittens...</p>
  </div>
</div>

But then I'd be sending the data twice: once in ng-init, and once in the HTML. I think I'd rather skip the ng-init attribute somehow.

Anyway do you think this is an okay approach?
Or is it not possible / bad, and I should do something else instead?

Is there any way to avoid including the data twice? (both in the html, and in ng-init)

like image 434
KajMagnus Avatar asked Nov 02 '22 15:11

KajMagnus


1 Answers

Seems like will be better to store all this data in json like:

   //...
   posts: [
      { postId : 123456,
        authorId : 789,
        text : 'Kittens ....' },
      { postId : 123457,
        authorId : 790,
        text : 'Puppies....' }
   ]
   //...

and then to populate it with ng-repeat like:

  <div ng-repeat="post in posts" id="{{post.postId}}"
     ng-controller="CommentCtrl" >     
     <div class="dw-p-hd">
       By <span data-dw-u-id="{{post.authorId}}">Kitty overlord</span>
     </div>
     <div class="dw-p-bd">
       <p>{{post.text}}</p>
     </div>
  </div>

I have similar issue , may be it will be useful for you: AngularJS - Getting data inserted in dom

like image 96
Ivan Chernykh Avatar answered Nov 11 '22 12:11

Ivan Chernykh