AngularJS:从HTML中的数据初始化模型?

前端之家收集整理的这篇文章主要介绍了AngularJS:从HTML中的数据初始化模型?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在考虑尝试从 HTML中的数据初始化(部分)AngularJS模型,而不是向服务器请求将数据作为 JSON获取,或者直接在页面中嵌入JSON对象.

(服务器目前只用HTML(而不是JSON)呈现数据,我现在想避免重写“太多”代码,而且HTML适用于搜索引擎.
应用程序本身是一个讨论系统.)

下面是我的HTML(简化)示例.其中嵌入的数据是帖子ID(123456),作者ID(789),作者姓名(Kitty霸主)和文本消息(“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>

我想构建一个AngularJS控制器,并将$scope初始化为:

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

也许我可以像这样使用ng-init:

<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>

但后来我要发送两次数据:一次在ng-init中,一次在HTML中.我想我不得不以某种方式跳过ng-init属性.

无论如何你认为这是一个好的方法吗?
或者它不可能/不好,我应该做别的事情呢?

有没有办法避免两次包含数据? (在html和ng-init中都有)

解决方法

似乎将所有这些数据存储在json中会更好:

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

然后用ng-repeat填充它,如:

<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>

我有类似的问题,可能对你有用:AngularJS – Getting data inserted in dom

猜你在找的Angularjs相关文章