繁体   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