简体   繁体   中英

AngularJS append HTML in the ng-repeat element

Using AngularJS I need to append HTML to the elements of ng-repeat, using the selector: '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>

so I created a loop to loop through the elements of the posts array, where for each element I call the function: 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 
    });
  });

This callback function gets a selector, elementParent, which we use to find the node in the DOM, and then apend the desired 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();
  };

But something does not work, as far as I'm concerned, the document.querySelector function can not find the selector.

It seems to me that when it tries to select, the node does not yet exist in the DOM.

I reproduced the code in the codepen , it might help.

How to Encapsulate jQuery code in a Custom Directive

Any jQuery code that manipulates the DOM should be encapsulated in a custom directive so that it is executed when the AngularJS framework ng-repeat directive instantiates the element.

<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);
    }
})

To use jQuery, simply ensure it is loaded before the angular.js file.

For more information, see

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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