我在角度js上关注了railscast#405,他使用的代码如下
app = angular.module("Raffler", ["ngResource"])
app.factory "Entry", ["$resource", ($resource) ->
$resource("/entries/:id", {id: "@id"}, {update: {method: "PUT"}})
]
@RaffleCtrl = ["$scope", "Entry", ($scope, Entry) ->
$scope.entries = Entry.query()
$scope.addEntry = ->
entry = Entry.save($scope.newEntry)
$scope.entries.push(entry)
$scope.newEntry = {}
$scope.drawWinner = ->
pool = []
angular.forEach $scope.entries, (entry) ->
pool.push(entry) if !entry.winner
if pool.length > 0
entry = pool[Math.floor(Math.random()*pool.length)]
entry.winner = true
entry.$update()
$scope.lastWinner = entry
]
我尝试在我的应用程序中使用几乎相同的代码实现非常类似的东西,唯一的问题是当调用drawWinner函数时,我的浏览器会记录错误“无法找到变量条目”但是函数中声明了变量条目的addEntry?
答案 0 :(得分:0)
JavaScript是功能范围的。 addEntry中的条目范围限定为$ scope.addEntry引用的函数,并且与forEach循环创建的变量不同...您需要重新检查变量范围。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope