簡體   English   中英

AngularJS在ng-repeat元素中附加HTML

[英]AngularJS append HTML in the ng-repeat element

使用AngularJS,我需要使用選擇器將HTML附加到ng-repeat元素:'objectMapParent-'+ post._id

  <div ng-repeat="post in posts">

    <div id="{{ 'objectMapParent-' + post._id }}">
      <h5 style="color:blue; margin-top: 3px;">{{post.title}}</h5>

    </div>
  </div>

所以我創建了一個循環以遍歷posts數組的元素的循環,對於每個元素,我在其中調用函數:createElement

 $scope.posts = [{
    _id: "1",
    title: "map of london"
  }, {
    _id: "2",
    title: "map of brazil"
  }, {
    _id: "3",
    title: "map of usa"
  }];

  $scope.posts.forEach(function(post) {
    // console.log(post);

    createElement("#objectMapParent-" + post._id, function() {
      //create map here after append 
    });
  });

該回調函數獲得一個選擇器elementParent,該選擇器用於在DOM中查找節點,然后附加所需的HTML

  var createElement = function(elementParent, cb) {

    var aux = elementParent;

    var postId = aux.replace("#objectMapParent-", "");

    var myElement = angular.element(document.querySelector(elementParent));

    var html = "<div id='objectMap-" + postId + "'><div id='BasemapToggle-" + postId + "'></div></div>";
    myElement.append(html);

    cb();
  };

但是有些事情行不通,就我而言,document.querySelector函數找不到選擇器。

在我看來,當它嘗試選擇時,該節點尚不存在於DOM中。

我在codepen中復制了代碼,可能會有所幫助。

如何在自定義指令中封裝jQuery代碼

任何處理DOM的jQuery代碼都應該封裝在一個自定義指令中,以便在AngularJS框架ng-repeat指令實例化該元素時執行。

<div ng-repeat="post in posts">
    <div id="{{ 'objectMapParent-' + post._id }}">
         <h5 style="color:blue; margin-top: 3px;">{{post.title}}</h5>
         <my-element post="post"></my-element>
    </div>
</div>
app.directive("myElement", function() {
    return {
        link: postLink,
    };
    function postLink(scope,elem,attrs) {
        var post = scope.$eval(attrs.post);
        var html = `
          <div id="objectMap-${post._id}">
            <div id="BasemapToggle-${post._id}">
            </div>
          </div>
        `;
        elem.append(html);
    }
})

要使用jQuery,只需確保已在angular.js文件之前加載了angular.js

有關更多信息,請參見

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM