如何使用AngularJs动态添加html内容

时间:2013-08-22 06:26:58

标签: angularjs

我想用angularJs动态添加HTML内容,但是获取和错误:

"$compile is not defined"

可能是什么原因?

代码

<td ng-repeat="user in users[0].yds" data-title="'Timeline'" sortable="timeline" style="text-align: center" >
    <div class="circle_dynamic"></div>
</td>


angular.module('elnApp')
  .controller('ProgramtableCtrl', function ($scope, $location, $filter, ngTableParams,    
     programTableService) {
        for(var i=0; i<=$scope.users[0].projects.length; i++){
            for(var j=0; j<$scope.users[0].projects[i].results.length; j++){

                if($scope.users[0].projects[i].results[j] == 0){

                    $(".circle_dynamic").html(
                      $compile(
                         ""
                      )(scope)
                    );
                    console.log('rm')
                }else{

                    $(".circle_dynamic").html(
                      $compile(
                         "<i ng-class='circle_class' style='position: absolute;'></i>"
                      )(scope)
                    );
                    console.log('add')
                }
            }

        }

    }, true);

}});

如何动态添加html内容?请帮忙

4 个答案:

答案 0 :(得分:0)

如果你只是想添加html内容ng-bindHtmlUnsafe就行了。

在HTML中

<div class="circle_dynamic" ng-bindHtmlUnsafe={{expression}}></div>

在控制器中

$scope.expression="<i ng-class='circle_class' style='position: absolute;'></i>"

请参阅文档here

答案 1 :(得分:0)

在angularjs中,作为最佳实践,您应该使用DOM操作的指令

为什么需要编译它?

答案 2 :(得分:0)

您无需在此处致电$compile

注意:硬编码索引$scope.users[0].projects.length对我来说在逻辑上似乎不正确,你确定要这么做吗?

代码中的这些行非常混乱。如果您告诉用户的数据结构(即用户,项目和结果之间的关系)和您想要实现的目标,那么您将更容易得到答案。

for(var i=0; i<=$scope.users[0].projects.length; i++){
    for(var j=0; j<$scope.users[0].projects[i].results.length; j++){

以下解决方案假设

users是一组用户。

每个user都有很多projects,因此user.projects是一个数组。

如果每个结果都存在,您希望为class="circle_class"显示一个div。

根据这些假设,以下内容应该足够了。

<td ng-repeat="user in users[0].yds"
    data-title="'Timeline'"
    sortable="timeline"
    style="text-align: center" >
  <div ng-repeat="project in user.projects">
    <div ng-repeat="result in project.results"
         ng-show="result">
      <i ng-class='circle_class' style='position: absolute;'></i>
      </div>
  </div>
</td>

答案 3 :(得分:0)

“未定义$ compile”是因为您忘记将其注入Controller。

使用$ compile动态添加HTML内容即可。但是不要在控制器中执行此操作。在指令中执行。

相关问题