[英]How can I pass this callback in Angular and update $scope?
I'm writing a basic game app in AngularJS. 我正在用AngularJS编写一个基本的游戏应用程序。 The game has
room
objects, some of which contain enemy
objects. 游戏中有
room
对象,其中一些包含enemy
对象。 I have a function to moveRoom()
which takes a callback parameter to run if the room contains an enemy
. 我有一个
moveRoom()
函数,如果房间包含enemy
该函数需要运行一个回调参数。
Inside this callback function, my $scope
changes don't register on ng-show
elements. 在此回调函数中,我的
$scope
更改未注册到ng-show
元素上。 I've tried combinations of $scope.apply()
and $scope.digest()
to no avail: 我试过
$scope.apply()
和$scope.digest()
组合无济于事:
$scope.moveToRoom = function (newRoom) {
// the callback here is only triggered if roomToMoveTo contains an enemy
manager.setCurrentRoom(roomToMoveTo, function($scope, encounterType, data) {
$scope.apply(function() {
if (encounterType === 'enemy') {
$scope.encounterMode = true;
}
});
});
};
... and the setCurrentRoom()
function (defined in another module) looks like this: ...,而
setCurrentRoom()
函数(在另一个模块中定义)如下所示:
var setCurrentRoom = function (room, callback) {
$scope.currentRoom = room;
if (callback) {
var enemies = room.getEnemies();
if (enemies.length > 0) {
callback($scope, 'enemy', enemies);
}
}
return $scope.currentRoom;
};
(You can see I've tried passing $scope
to the callback function but this hasn't helped). (您可以看到我已尝试将
$scope
传递给回调函数,但这没有帮助)。
The error I get is Error: $scope.apply is not a function
, or if I remove that, I get no UI changes (that I'd expect from ng-show="encounterMode"
). 我得到的
Error: $scope.apply is not a function
是Error: $scope.apply is not a function
,或者如果我删除了它,则不会得到UI更改(我希望从ng-show="encounterMode"
)。
Only thing that I can think of that might be breaking things is the way I share $scope
between modules – the manager
module is another file loaded via requireJS – it returns a function which takes a $scope
parameter, so I initialise the manager
module with $scope
so all its methods have access to the global scope. 只有我能想到的,可能会被打破的事情的是我分享的方式
$scope
模块之间-的manager
模块是通过requireJS加载另一个文件-它返回一个函数,它接受一个$scope
参数,所以我初始化manager
模块$scope
因此其所有方法都可以访问全局范围。 Not sure if there's a better way to do this when mixing Angular with AMD JavaScript. 不确定将Angular与AMD JavaScript混合使用时是否有更好的方法。
Is there something I'm missing here about making this callback update the scope? 关于此回调更新作用域,我这里缺少什么吗? Am I passing it wrongly?
我是错误地通过了吗?
EDIT: As TJ points out, I have a typo which should be $apply
– having fixed this, I'm now seeing Error: $rootScope:inprog Action Already In Progress . 编辑:正如TJ所指出的,我有一个错字应该是
$apply
-修正了这个问题,我现在看到错误:$ rootScope:inprog操作已在进行中 。 Have a feeling I'm still approaching this wrongly? 感觉我仍在错误地处理这个问题吗?
You seem to have a typo. 您似乎有错字。
apply
code should be $apply
apply
代码应为$apply
$scope.$apply(function() {
//-----^ this thing
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.