0

我是 AngularJS 的新手,我试图想象自己,如何用 Angular 来完成这个场景:

假设我们有 20 个不同的 div:

<div id="div0"></div>
<div id="div1"></div>
...
<div id="div19"></div>

现在,在一些控制器中,我们正在加载 JSON,fe:

[
{label: "Lorem ipsum", position: "div0"},
{label: "Dolor", position: "div2"},
{label: "Lorem ipsum", position: "div8"}
]

现在,我想渲染这些元素,所以输出将是,对于第一个 JSON 对象:

{label: "Lorem ipsum", position: "div0"}-> <p>{{label}}</p>-><p>Lorem</p>

并将其附加到#div0.

4

2 回答 2

1

如果我理解你的问题,我认为这就是答案:

app.controller('MyCtrl', function($scope) {
   $scope.items = [
      {label: "Lorem ipsum", position: "div0"},
      {label: "Dolor", position: "div2"},
      {label: "Lorem ipsum", position: "div8"}
   ];
});

这是标记:

<div ng-repeat="item in items" id="{{item.position}}"><p>{{item.label}}</p></div>

这就是它的全部内容。

编辑

OP 想将数据放入硬编码的 HTML 中……所以你可以这样做:

app.controller('MyCtrl', function($scope) {
   $scope.items = [
      {label: "Lorem ipsum", position: "div0"},
      {label: "Dolor", position: "div2"},
      {label: "Lorem ipsum", position: "div8"}
   ];

   $scope.getValue = function(position) {
      for(var i = 0; i < $scope.items.length; i++) {
        var item = $scope.items[i];
        if(item.position == position) {
            return item.label;
        }
      }
      return '';
   };
});

像这样标记:

<div id="div0">{{getValue('div0')}}</div>
<div id="div1">{{getValue('div1')}}</div>
<div id="div8">{{getValue('div8')}}</div>
于 2012-11-09T13:38:19.280 回答
0

If you have control over the JSON that is returned from the server, the following would simplify things:

Controller/JSON:

$scope.contents = {
    content0: "Lorem",
    content1: "lpsum"
};

Markup:

<div>{{contents.content0}}</div>
<div>{{contents.content1}}</div>

In jQuery, we normally think of associating content/DOM changes with IDs.
In Angular, we try to declare where the content should go, without the use of IDs.

于 2012-11-09T22:28:13.147 回答