1

我的 Angular 应用程序具有以下代码:

index.jade:

doctype 5
html
    head

    body(ng-app='app')
        div(ng-controller='EventController')
            div(ng-repeat='event in list()')
                h2 {{event.name}}
                h3 {{event.location}}

            h2 Create new event
            label(for='name') Name:
            input(ng-model='name')

            label(for='location') Location:
            input(ng-model='location')
            button(ng-click='create()') Submit

        script(src='https://ajax.googleapis.com/ajax/libs/angularjs/1.1.5/angular.js')
        script(src='https://ajax.googleapis.com/ajax/libs/angularjs/1.1.5/angular-resource.js')

        script(src= 'javascripts/app.js')

app.coffee:

app = angular.module 'app', ['ngResource']

EventsFactory = ($resource, $q)->
    url = 'http://localhost:3000/events'
    resource = $resource(url)
    resourceWithId = $resource("#{url}/:id", {id: '@id'})

    list = (events)->
        deferred = $q.defer()
        resource.get(
            (events)-> 
                deferred.resolve events
            ,(response)-> 
                deferred.reject response 
            )
        return deferred.promise

    create = (event)->
        deferred = $q.defer()
        resource.save(
            event
            ,(response)->
                deferred.resolve response
            ,(response)->
                deferred.reject response
            )
        return deferred.promise  

    ret =  
        'list': list
        'create': create
    return ret

app.factory 'EventsFactory', EventsFactory


EventController = ($scope, EventsFactory)->
    $scope.event = {}

    $scope.list = (events)->
        EventsFactory.list(events).then(
            (events)-> 
                console.log events
            ,(response)-> 
                console.log response
            )

    $scope.create = (event)->
        EventsFactory.create(event).then(
            (response)-> 
                console.log 'success', response
            ,(response)->
                console.log 'failure', response
            )
app.controller 'EventController', EventController

但是当我转到主页时,应用程序挂起,并且控制台有一条错误消息,开头为: 10 $digest() 达到了迭代。我究竟做错了什么?

4

2 回答 2

3

不要list()在您的ng-repeat.

发生的情况是ng-repeat指令在填充模型时重新评估模型并导致无限迭代。

您将需要分配一个$scope变量并使用它。

请原谅 javascript,不流利的咖啡。

$scope.theList = $scope.list();

然后在您的 html 中,更改:

ng-repeat="event in list()"

ng-repeat="event in theList"
于 2013-10-08T04:54:54.837 回答
0

您应该将列表的结果分配给这样的范围变量

$scope.events=$scope.list();

然后你可以在 ng-repeat 中使用这个变量

   div(ng-repeat='event in events')
            h2 {{event.name}}
            h3 {{event.location}}
于 2013-10-08T05:24:34.150 回答