Angularjs在单击时向DOM添加元素

时间:2015-11-19 13:05:43

标签: javascript html angularjs dom add

我想创建一个包含动态内容的表。单击元素时,详细信息应显示在下一行中。所以我创造了以下内容:

<table ng-controller="TestCtrl">
    <tr ng-repeat-start="word in ['A', 'B', 'C']">
        <td><!-- Some Information, Image etc --></td>
        <td ng-click="showDetails(word)">{{word}}</td>
    </tr>

    <!-- This is only visible if necessary -->
    <tr ng-repeat-end ng-show="currentDetail == word">
        <td colspan="2" ng-attr-id="{{'Details' + word}}"></td>
    </tr>
</table>

我有以下js代码:

angular.module('maApp', []).controller("TestCtrl", function($scope, $document, $compile){
    $scope.showDetails = function(word){
        var target = $document.find("Details" + word);

        //I checked it - target is NOT null here

        //target.html("<div>Test</div>");
        //target.append("<div>Test</div>");
        var el = $compile("<div>Test</div>")($scope);
        target.append(el);

        //Show tr
        $scope.currentDetail = word;
    };
});

我也尝试过以上评论的解决方案,但没有任何效果(然而tr却出现了)。我想$document.find("Details" + word)有问题,但我不知道是什么。

最终我要添加<iframe>,来源将包含word

有人看到我在这里做错了吗?

3 个答案:

答案 0 :(得分:1)

$ jcite中的document.find仅限于标记名称。你必须添加jquery以获得更多。 查看docs中支持的内容。

答案 1 :(得分:1)

不需要奇怪的非棱角分明的DOM操作:你只需要这个。

HTML:

<table ng-controller="TestCtrl">
    <tr ng-repeat-start="word in ['A', 'B', 'C']">
        <td><!-- Some Information, Image etc --></td>
        <td ng-click="showDetails(word)">{{word}}</td>
    </tr>
    <tr ng-show="currentDetail==word" ng-repeat-end>
        <td colspan="2">Details {{word}}</td>
    </tr>
</table>

JS:

angular.module('myApp', []).controller("TestCtrl", function($scope, $document, $compile){
    $scope.showDetails = function(word) {
        $scope.currentDetail = word;
    };
});

http://jsfiddle.net/HB7LU/20074/

答案 2 :(得分:1)

你已经将所有需要内置到角度中,你根本不需要Javascript。

请参阅this plunker example

  <table style="width:100%;">
    <thead style="background-color: lightgray;">
      <tr>
        <td style="width: 30px;"></td>
        <td>
          Name
        </td>
        <td>Gender</td>
      </tr>  
    </thead>
    <tbody>
      <tr ng-repeat-start="person in people">
        <td>
          <button ng-if="person.expanded" ng-click="person.expanded = false">-</button>
          <button ng-if="!person.expanded" ng-click="person.expanded = true">+</button>
        </td>
        <td>{{person.name}}</td>
        <td>{{person.gender}}</td>
      </tr>
      <tr ng-if="person.expanded" ng-repeat-end="">
        <td colspan="3">{{person.details}}</td>
      </tr>
    </tbody>
  </table>