简体   繁体   English

AngularJS-将元素追加到指定的DOM元素

[英]AngularJS - Append element to specified DOM element

I'm new to AngularJS and i'm trying to imagine myself, how to do this scenario with angular: 我是AngularJS的新手,我试图想象自己,如何使用angular实现此方案:

Let's say we have 20 difftent divs: 假设我们有20个不同的div:

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

Now, in some controller we are loading JSON, fe: 现在,在某些控制器中,我们正在加载JSON,fe:

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

Now, I want to render this elements, so the output will be, for the first JSON object: 现在,我想呈现此元素,因此输出将是第一个JSON对象:

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

and append this to #div0 . 并将其附加到#div0

If I understand your question I think this is the answer: 如果我了解您的问题,我认为这是答案:

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

and here's the markup: 这是标记:

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

That's pretty much all there would be to it. 这几乎就是它的全部。

EDIT 编辑

The OP would like to place the data into hard-coded HTML... so do to that you could do something like this: 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 '';
   };
});

Markup like so: 像这样标记:

<div id="div0">{{getValue('div0')}}</div>
<div id="div1">{{getValue('div1')}}</div>
<div id="div8">{{getValue('div8')}}</div>

If you have control over the JSON that is returned from the server, the following would simplify things: 如果您可以控制从服务器返回的JSON,则以下内容将简化操作:

Controller/JSON: 控制器/ 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. 在jQuery中,我们通常考虑将内容/ DOM更改与ID相关联。
In Angular, we try to declare where the content should go, without the use of IDs. 在Angular中,我们尝试声明内容应该去的地方,而不使用ID。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM