虽然angular.forEach
只返回personList
的最后一个值。
如何为personList中的每个对象显示已创建directive
的信息?
我需要在forEach循环中完全解决。
var app = angular.module('MyApp', [])
app.controller('MyController', function ($scope, $compile) {
var personList = [
{ name: "John", age: "20" },
{ name: "Peter", age: "25" }
];
angular.forEach(personList, function(p, i) {
$scope.person = { name: personList[i].name, age: personList[i].age };
var personInfo = ($compile)('<person-info></person-info>')($scope);
var body = document.querySelector("body")
var parentDiv = document.createElement("div");
body.append(parentDiv);
parentDiv.append(personInfo[0]);
});
});
app.directive("personInfo", function () {
return { template: '{{ person.name }} is {{person.age}} years old' }
});
在Html中:
Peter is 25 years old
Peter is 25 years old