2016-05-30 174 views
1

我已經創建了基於使用jquery的數組值的動態div。它工作正常,以下是jQuery的代碼,Angular js動態div創建

$(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); 
     } 
    }); 
}); 

但我需要在角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)); 
} 

我需要幫助。

+0

爲此編寫指令 –

+0

如何爲此函數編寫指令。 – jicks

回答

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/

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> 
+0

記得包括角衛生。 –