3

很长一段时间以来,我一直把头撞在墙上,试图弄清楚这一点。我正在尝试更新 AngularJS 中 $scope 的一部分的数组中的数组。

$scope 实际上确实会更新,如 console.log 所示,但 ng-repeat 无法添加新元素。我试过 $scope.$apply,但它说它已经在运行。我错过了什么?

<div ng-controller="myCtrl">

    <div ng-repeat="event in events">
        <span>The next event is happening on {{event.eventDate}}</span>
        <ul>
            <li ng-repeat="attendee in event">{{event.attendees[$index]}}</li>
        </ul>
        <form ng-submit="addAttendee($index)">
            <input type="text" ng-model="attendeeText" placeholder="add a new attendee here" />
            <input type="submit" value="add attendee" />
        </form>
        <hr />
    </div>

</div>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
<script>
    function myCtrl($scope) {
        $scope.events = [
            {eventDate:'25/09/2013',attendees:['Pinky','The Brian']},
            {eventDate:'30/10/2013',attendees:['Robocop','The Terminator']}
        ];

        $scope.addAttendee = function(index) {
            $scope.events[index].attendees.push(this.attendeeText);
            console.log(JSON.stringify($scope.events[index]));
            this.attendeeText = '';
        };
    };
</script>

在此先感谢,如果这是我的一个明显的错误,我们深表歉意!

4

2 回答 2

4

您不是要求它显示添加的项目。更改此行

<ul>
   <li ng-repeat="attendee in event">{{event.attendees[$index]}}</li>
</ul>

<ul>
   <li ng-repeat="attendee in event.attendees">{{attendee}}</li>
</ul>
于 2013-09-26T11:58:39.880 回答
0

请试试这个

HTML

    <div  ng-app  ng-controller="myCtrl">

<div ng-repeat="event in events">
    <span>The next event is happening on {{event.eventDate}}</span>
    <ul>
        <li ng-repeat="attendee in event.attendees">{{attendee}}</li>
    </ul>
    <form ng-submit="addAttendee($index)">
        <input type="text" ng-model="attendeeText" placeholder="add a new attendee here" />
        <input type="submit" value="add attendee" />
    </form>
    <hr />
</div>


       </div>

JS

    function myCtrl($scope) {
    $scope.events = [
        {eventDate:'25/09/2013',attendees:['Pinky','The Brian']},
        {eventDate:'30/10/2013',attendees:['Robocop','The Terminator']}
    ];

    $scope.addAttendee = function(index) {
        $scope.events[index].attendees.push(this.attendeeText);
        console.log(JSON.stringify($scope.events[index]));
        this.attendeeText = '';
    };
};

你也可以参考下面的小提琴

http://jsfiddle.net/U3pVM/1457/

于 2013-09-26T12:05:51.130 回答