【发布时间】:2014-04-04 01:00:29
【问题描述】:
我是 Angular 的新手,所以如果我的方法不是惯用的,我提前道歉。我试图在控制器中找到的placeShot() 函数中附加一个<circle> 元素,该函数是从ng-click='placeShot($event) 调用的。
我目前还在ng-init 内硬编码#basketball-container 的宽度。由于我的页面是响应式的,我想获取这个元素的宽度(在不同的设备上会有所不同),然后根据这个值创建<svg>#basketball-court。
HTML
<div ng-app="myApp">
<div id="basketball-container" ng-controller="BasketballCtrl" ng-init="width=400; height=width*0.75">
<h3>Width: {{width}}, Height: {{height}} - Hardcoded</h3>
<svg id="basketball-court" ng-attr-height="{{height}}" ng-attr-width="{{width}}" ng-click="placeShot($event)">
<!-- Boundary -->
<line x1="0" y1="0" x2="0" y2="{{height}}" class="boundary" />
<line x1="0" y1="0" x2="{{width}}" y2="0" class="boundary" />
<line x1="0" y1="{{height}}" x2="{{width}}" y2="{{height}}" class="boundary" />
<line x1="{{width}}" y1="0" x2="{{width}}" y2="{{height}}" class="boundary" />
<!-- 3 Pt Arc -->
<path d="M {{0.11*width}} 0 V {{0.1*height}}" />
<path d="M {{0.89*width}} 0 V {{0.1*height}}" />
<path d="M {{0.11*width}} {{0.1*height}} C {{0.11*width}} {{height}}, {{0.89*width}} {{height}}, {{0.89*width}} {{0.1*height}}" fill="transparent"/>
<!-- Key Outline -->
<path d="M {{0.35*width}} 0 v {{0.57*height}} h {{0.3*width}} v -{{0.57*height}}" fill="transparent"/>
<!-- Top of Key -->
<circle cx="{{width/2}}" cy="{{0.57*height}}" r="{{0.15*width}}" fill="transparent" />
<!-- Backboard -->
<path d="M {{0.41*width}} {{0.033*height}} h {{0.18*width}}" />
<!-- Basket -->
<circle cx="{{width/2}}" cy="{{0.08*height}}" r="{{0.03*width}}" fill="transparent" />
</svg>
</div>
</div>
角度
var myApp = angular.module('myApp',[]);
myApp.controller('BasketballCtrl', ['$scope', '$element', function($scope, $element) {
$scope.placeShot = function(event) {
var x = event.offsetX;
var y = event.offsetY
console.log($element);
console.log(x);
console.log(y);
var html = '<circle cx="'+ x.toString() +'" cy="'+ y.toString() +'" r="10" class="shot" />';
console.log(html);
// Append shot to <svg>
$("#basketball-court").append(html);
};
}]);
这里是 JSFiddle 的链接:http://jsfiddle.net/Abundnce10/426LX/6/
我最初的问题是:如何在 placeShot() 函数中附加 <circle> 元素?但我很高兴听到我应该如何重组我的代码以更符合 Angular 最佳实践。
基本上,我有一个响应式页面,所以我想获取<svg> 的父元素的宽度,然后允许该值驱动它的大小。我还想让用户点击球场,在球场上一个新的<circle> 元素将标记这项运动。这似乎是一项简单的任务,但我在使用 Angular 时遇到了麻烦。我欢迎所有建议/反馈。谢谢!
【问题讨论】:
标签: angularjs svg angularjs-directive angularjs-scope