【问题标题】:AngularJS append HTML in the ng-repeat elementAngularJS 在 ng-repeat 元素中附加 HTML
【发布时间】:2019-04-28 22:07:38
【问题描述】:

使用 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>

所以我创建了一个循环来遍历帖子数组的元素,其中对于每个元素我调用函数: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中的代码,可能会有帮助。

【问题讨论】:

  • 不确定我是否理解您为什么不直接从视图中构建此结构,是因为您需要在追加后创建该地图吗?因为您可以使用ngInit 指令并从视图中调用该函数
  • 您为什么要尝试手动操作? angularjs模板有什么问题?
  • @AlonEitan 我不能将 document.querySelector 用于 ng-repeat 项目。我不理解为什么。这对我的项目非常重要。
  • 避免在控制器中进行 DOM 操作。而是使用 custom directives 添加 DOM。在使用 ng-repeat 指令时尤其如此,该指令在其操作过程中添加和销毁 DOM。 querySelector 找不到该元素,因为 ng-repeat 指令尚未添加它。

标签: javascript angularjs angularjs-ng-repeat


【解决方案1】:

如何在自定义指令中封装 jQuery 代码

任何操作 DOM 的 jQuery 代码都应该封装在 custom directive 中,以便在 AngularJS 框架 ng-repeat directive 实例化元素时执行。

<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 文件之前加载。

有关详细信息,请参阅

【讨论】:

  • @georgeawg 你是绝对正确的,但是我添加的 dojo 小部件在添加它们时会出错 ng-repeat,我想尝试通过控制器附加这些小部件。谢谢
猜你喜欢
  • 2012-10-03
  • 2018-04-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-18
  • 1970-01-01
相关资源
最近更新 更多