这个错误绝对让我发疯,我似乎无法修复它。我有一个下拉列表,当用户选择一个新选项时,它会自动动态更新。我正在使用的对象是我创建的“房间”对象,我正在努力使用当用户选择哪个可用房间应该在他们正在编辑的当前房间的北面时,所选择的房间是南值设置为当前正在编辑的房间,正在编辑的房间的北值将设置为所选房间。
我的代码在我工厂的addNorth函数中抛出错误(我尝试了Room.prototype和直接工厂函数)我尝试设置newRoom.south = _selectedRoom
当我在console.log newRoom(这是基于我的ng-model添加为cardinalRooms.north的房间对象)时,记录的房间是一个有效的对象,这增加了我的困惑。
抛出的错误状态:“TypeError:无法设置null的属性'south'”。我怀疑它与如何将每个Room对象的东,西,南和北初始化为null有关,但是对于我的一些功能我将它们初始化为null并且认为这样做是相当常见的。
这是相关的HTML
<select ng-options="n.name for n in north" ng-model="cardinalRooms.north" ng-change="updateNorth()">
<option>
</option>
</select>
这是处理所有Room对象的相关RoomManager工厂代码
.factory('RoomManager', function () {
var _rooms = [];
var _selectedRoom = {};
var Room = function (name) {
this.name = name;
this.east = null;
this.west = null;
this.north = null;
this.south = null;
}
//Add a room to the north of a given room
Room.prototype.addNorth = function (newRoom) {
if (this.north != null) {
this.north.south = null;
}
this.north = newRoom;
newRoom.south = this;
}
//Add a room to the north of a given room
function addNorth(newRoom) {
if (_selectedRoom.north != null) {
_selectedRoom.north.south = null;
}
_selectedRoom.north = newRoom;
newRoom.south = _selectedRoom;
}
//Gets all possible valid North rooms
function getNorthRooms() {
var northRooms = [];
for (var i = 0; i < _rooms.length; i++) {
//Rooms must have no south to be able to be a North room
if (_rooms[i].south == null && _rooms[i] != _selectedRoom && _rooms[i] != _selectedRoom.east && _rooms[i] != _selectedRoom.south && _rooms[i] != _selectedRoom.west) {
northRooms.push(_rooms[i]);
}
}
return northRooms;
}
return {
addNorth: addNorth,
getNorthRooms: getNorthRooms
}
})
最后是相关的控制器代码
.controller('EditRoomCtrl', function ($scope, GameManager, RoomManager) {
//Object for ng-model
$scope.cardinalRooms = {};
$scope.north = [];
$scope.east = [];
$scope.south = [];
$scope.west = [];
//Function to update room options for N, E, S, W
$scope.updateRooms = function () {
$scope.north = RoomManager.getNorthRooms();
$scope.east = RoomManager.getEastRooms();
$scope.south = RoomManager.getSouthRooms();
$scope.west = RoomManager.getWestRooms();
}
//Call the function to assign init values
$scope.updateRooms();
$scope.updateNorth = function () {
$scope.selectedRoom.addNorth($scope.cardinalRooms.north);
$scope.updateRooms();
}
//Load rooms to room manager from selected game in game manager
RoomManager.loadRooms(GameManager._selectedGame);
//Assign to scope
$scope.rooms = RoomManager.getRooms();
$scope.selectedRoom = RoomManager.getSelectedRoom();
//Assign values for ng-model
$scope.cardinalRooms.north = $scope.selectedRoom.north;
$scope.cardinalRooms.east = $scope.selectedRoom.east;
$scope.cardinalRooms.south = $scope.selectedRoom.south;
$scope.cardinalRooms.west = $scope.selectedRoom.west;
});
$ scope.selectedRoom只是之前分配的RoomManager工厂中的一个变量。