使用 Angular 指令从数组生成 html

Use an Angular directive to generate html from an array

我正在尝试使用 Angular 指令创建一个表单,用户可以在其中指定 children 的数量,并且对于每个 child,都会出现一个编辑框允许输入 child 的出生日期。

这是我的 HTML:

<div ng-app>
  <div ng-controller="KidCtrl">
    <form>
    How many children:<input ng-model="numChildren" ng-change="onChange()"/><br/>
    <ul>
        <li ng-repeat="child in children">
            <child-dob></child-dob>
        </li>
      </ul>
    </form>
  </div>
</div>

这是 JS:

var app=angular.module('myApp', []);

function KidCtrl($scope) {
  $scope.numChildren = 2
  $scope.children = [{dob: "1/1/90"}, {dob: "1/1/95"}];
  $scope.onChange = function () {
    $scope.children.length = $scope.numChildren;
  }
}

app.directive('childDob', function() {
    return {
      restrict: 'E',
      template: 'Child {{$index+1}} - date of birth: <input ng-model="child.dob" required/>'
    };
  });

这里是a jsFiddle

问题是它无法正常工作。 如果我在 numChildren 字段中输入 1,那么它会为列表元素显示 1 个项目符号点,但不会显示任何 HTML。 如果我在 numChildren 字段中输入 2,则它不会显示任何列表元素。

谁能解释我做错了什么?

非常感谢...

您的主要问题是从未呈现指令 childDOB。即使您的控制器可以工作,因为 angular 的 1.2.x 版本启用了全局控制器发现功能。它将在全局范围内查找任何 public 构造函数以匹配 ng-controller 指令中的控制器名称。指令不会发生。因此,缺少 ng-app="appname" 就无法呈现指令。所以添加 appname ng-app="myApp" 并查看它是否正常工作。不要污染全局范围并使用 controller() 构造函数正确注册控制器也是一个好习惯。 (无论如何,从 1 开始,全局查找已被弃用。3.x 并且只能在全局级别关闭。)

您还需要在 ng-repeat 中添加 track by,因为根据文本框值增加数组长度可能会出现重复器。它可能导致多个数组值未定义,从而导致重复。所以:-

 ng-repeat="child in children track by $index"

Fiddle

Html

<div ng-app="myApp">
    <div ng-controller="KidCtrl">
        <form>How many children:
            <input ng-model="numChildren" ng-change="onChange()" />
            <br/>
            <ul>
                <li ng-repeat="child in children track by $index">{{$index}}
                    <child-dob></child-dob>
                </li>
            </ul>
        </form>
    </div>
</div>

脚本

(function () {

    var app = angular.module('myApp', []);

    app.controller('KidCtrl', KidCtrl);

    KidCtrl.$inject = ['$scope'];
    function KidCtrl($scope) {
        $scope.numChildren = 2
        $scope.children = [{
            dob: "1/1/1990"
        }, {
            dob: "1/1/1995"
        }];
        $scope.onChange = function () {
            $scope.children.length = $scope.numChildren;
        }
    }

    app.directive('childDob', function () {
        return {
            restrict: 'E',
            template: 'Child {{$index+1}} - date of birth: <input ng-model="child.dob" required/>'
        }
    });
})();