angularjs指令与数组

时间:2018-04-25 17:08:44

标签: angularjs binding scope compilation directive

虽然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

0 个答案:

没有答案