我正在为在线棋盘游戏制作网络界面。我想用Snap.load加载 Snap.svg 地图,即异步加载。
加载后,我想在范围的属性中添加一个手表,并根据属性(这是一个对象)为地图添加一些颜色。我的代码基本上是这样的:
.controller('GameCtrl', [
'$scope'
'$routeParams'
'GameService'
(
$scope
$routeParams
GameService
) ->
$scope.game = GameService.get($routeParams.gameId)
$scope.map = Snap("#map")
Snap.load("img/classical.svg", (data) ->
console.log "Loaded map!"
data.select("#provinces").attr
style: ""
provinces = data.selectAll("#provinces path")
for province in provinces
province.attr
style: ""
fill: "#FFFFFF"
"fill-opacity": "0"
$scope.map.append(data)
deregisterWatch = $scope.$watch('game', ->
console.debug "Game loaded!", $scope.game.data.Id
for provinceName,unit of $scope.game.data.Phase.Units
provinceName = provinceName.replace '/', '-'
province = $scope.map.select("##{provinceName}")
province.attr
style: ""
fill: powers[unit.Nation].colour
"fill-opacity": "0.8"
deregisterWatch()
)
)
])
现在,问题是我想将地图移动到它自己的“类”或文件中,但它必须以$scope
某种方式知道,以便能够在加载后设置手表。
我的第一个天真的方法是提取地图并传入范围:
define([
'snap'
], (
Snap
) ->
'use strict'
Map = ($scope, selector, svgPath) ->
that = {}
that.provinces = {}
...
that.snap = Snap(selector)
Snap.load(svgPath, (data) ->
console.log "Loaded map in Map!"
data.select("#provinces").attr
style: ""
provinces = data.selectAll("#provinces path")
for province in provinces
that.provinces[province.attr("id")] = province
province.attr
style: ""
fill: "#FFFFFF"
"fill-opacity": "0"
that.snap.append(data)
deregisterWatch = $scope.$watch('game', ->
console.debug "Game loaded!", $scope.game.data.Id
for provinceName,unit of $scope.game.data.Phase.Units
provinceName = provinceName.replace '/', '-'
that.colourProvince(provinceName, that.powerColors[unit.Nation].colour)
deregisterWatch()
)
)
that.colourProvince = (abbr, colour) ->
...
return that
return Map
)
但我认为必须有一种更角度的方式来做到这一点。我应该做一个指令吗?还有什么建议吗?