Angular js动态div创建

时间:2016-05-30 03:45:09

标签: jquery html angularjs dynamic-content

我使用jquery在数组值的基础上创建了动态div。它工作正常,以下是jquery的代码,

$(document).ready(function () {
    var i = 1;
    var arr = ["a", "b", "c"];
    /*arr=;*/
    //arr = doc.slice();

    $(window).load(function () {
        alert(arr[1] + ":" + arr.length);
        for (i = 0; i < arr.length; i++) {
            var ele = document.createElement("div");
            ele.setAttribute("id", "child" + i);
            ele.setAttribute("class", "span4 greenDark");
            ele.innerHTML = '<object type="text/html" data="iindex.html" ></object>';
            document.getElementById("mydiv").appendChild(ele);
        }
    });
});

但我需要在angular js ng-init方法调用中执行相同的功能。但角度代码不会产生任何div。 我试过以下代码,

var arr = ["a", "b", "c"];
alert("load" + arr);

for (i = 0; i < arr.length; i++) {
    alert("load" + arr[i]);
    var ele = document.createElement("div");
    ele.setAttribute("id", "child" + i);
    ele.setAttribute("class", "span4 greenDark");
    ele.innerHTML = '<object type="text/html" data="iindex.html" ></object>';

    // angular.element(document.getElementById("mydiv").appendChild(ele));
    angular.element(document.getElementById('mydiv')).append($compile("<div><button class='btn btn-default' data-alert=" + scope.count + ">Show alert #" + scope.count + "</button></div>")(scope));
}

我需要帮助。

2 个答案:

答案 0 :(得分:1)

<div my-directive myarray="myarray"></div>



  angular.module('sampleApp', [])
  .controller('myCtrl', function($scope) {
    $scope.myarray = ["a","b","c"];
  })
  .directive("myDirective", function($compile) {
    return {
      template: "<div></div>",
      restrict: 'EA',
      scope: {
        myarray: '='
      },
      link: function(scope, element, attrs) {  
         var template='<div ng-repeat="item in myarray"><button class="btn btn-default" >item#{{$index}}</button></div>';

            var linkFn = $compile(template);
            var content = linkFn(scope);
            element.append(content);
      }

    }
  });

结帐小提琴https://jsfiddle.net/ebinmanuval/rpjacmy2/3/

答案 1 :(得分:0)

Controller

创建一个函数来返回此HTML:

function initButton () {

  var arr = ['a', 'b', 'c'];
  var html = '';

  for (var i = 0, length = arr.length; i < length; i++) {
    html += "<div><button class='btn btn-default' data-alert=" + i + ">Show alert #" +i"</button></div>";
  }

  return html; 

}


$scope.buttonHTML = initButton();

View

<div ng-bind-html="buttonHTML"></div>