在ng-submit上将文本推送到范围内的数组时,ng-repeat不会更新

时间:2013-09-26 11:46:58

标签: javascript angularjs

我一直在靠墙撞击,试图在一段令人尴尬的时间里弄清楚这一点。我正在尝试更新一个数组中的数组,该数组是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>

提前致谢,对不起,如果这对我来说是一个非常明显的错误!

2 个答案:

答案 0 :(得分:3)

您不是要求它显示添加的项目。改变这一行

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

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

答案 1 :(得分: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/