这是一个稍长的。如何让儿童指令知道所有父母的角度?
我怎样才能知道所有的祖先,而不仅仅是他们的直接父母的子指令?
我问的原因是我想要一张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>
可能想要共享数据的服务,可以通过任何控制器或指令 – charlietfl