这是一个略长的。
我怎样才能让子指令知道他们所有的祖先,而不仅仅是他们的直接父母?
我问的原因是我想要一个 Raphael 论文指令,为所有子项提供对 Raphael 论文的引用。另外,我试图有一个“rl-shape”指令,可以将不同的形状组合在一起,这样它们就可以一起翻译、转换等。我还希望这个“rl-shape”指令能够出现在自身内部,允许任意形状的树。
可能有一种完全不同的更好的方法来做到这一点。如果是这样,请纠正我。
这是我到目前为止的代码:
<!doctype html>
<html xmlns:ng="http://angularjs.org" ng-app="myApp">
<head>
<title>Test</title>
<script src="js/underscore.js"></script>
<script src="js/raphael-min.js"></script>
</head>
<body>
<rl-paper>
<rl-shape name="myShape">
<rl-circle name="inner" cx="0" cy="0" r="50"></rl-circle>
<rl-circle name="outer" cx="0" cy="0" r="100"></rl-circle>
</rl-shape>
</rl-paper>
<p>
<button ng-click="myShape.translate(0, -10)">Move shape up</button>
<button ng-click="myShape.translate(0, 10)">Move shape down</button>
</p>
<script src="js/angular.min.js"></script>
<script>
var myApp = angular.module("myApp", []);
function Shape(children) {
this.translate = function(dx, dy) {
_.each(children, function(c) { c.translate(dx, dy); });
};
}
myApp.directive("rlPaper", function() {
return {
restrict: "E",
controller: function($element) {
this.paper = new Raphael($element[0], 220, 220);
this.paper.setViewBox(-110, -110, 220, 220);
}
};
});
myApp.directive("rlShape", function () {
return {
restrict: "E",
require: ["^rlPaper"],
controller: function($scope, $element, $attrs, $transclude) {
this.children = [];
},
link: function(scope, element, attrs, ctrls) {
// How can the link function of the rlShape directive access its
// own controller? If I could figure that out, I could do
// something like the following:
var shapeCtrl = undefined; // Don't know how to get this
var shape = Shape(shapeCtrl.children);
scope[attrs.name] = shape;
}
};
});
myApp.directive("rlCircle", function() {
return {
restrict: "E",
require: ["^rlPaper", "?^rlShape"],
link: function(scope, element, attrs, ctrls) {
var paperCtrl = ctrls[0];
var shapeCtrl = ctrls[1];
var circle = paperCtrl.paper.circle(attrs.cx, attrs.cy, attrs.r);
scope[attrs.name] = circle;
if ( shapeCtrl ) {
shapeCtrl.children.push(circle);
}
}
};
});
</script>
</body>
</html>