5

我正在考虑尝试从 HTML 中的数据初始化(部分)AngularJS 模型,而不是向服务器发出请求以将数据作为 JSON 获取,或者直接在页面中嵌入 JSON 对象。

(服务器目前只以 HTML(不是 JSON)呈现数据,我现在想避免重写“太多”代码,并且 HTML 与搜索引擎配合得很好。应用程序本身就是一个讨论系统。)

下面是我的 HTML 示例(简化)。其中嵌入的数据是帖子ID(123456)、作者ID(789)、作者姓名(Kitty overlord)和短信(“Kittens Cats!开玩笑吧。)。

<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

4

1 回答 1

2

似乎将所有这些数据存储在 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

于 2013-08-27T06:02:22.780 回答