[英]In AngularJS how to access multiple child scopes from parent scope
I have a parent zone builder
controller which has multiple US States
that can have several zip codes within each state. 我有一个父zone builder
控制器,该控制器具有多个US States
,每个州内可以有多个邮政编码。
Here is a breakdown of the basics of the format: 以下是该格式的基本知识:
BUILDER CONTROLLER 建筑控制器
app.controller("builderController", function($scope, $http, $rootScope, $timeout) {
$scope.zones = [];
});
ZIP CONTROLLER 邮编控制器
app.controller("zipController", function($scope, $http, $rootScope, $timeout) {
$scope.zipCodes = [];
$scope.addZipCode = function() {
$scope.zipCodes.push({code: '', distance: '25mi'});
}
$scope.removeZipCode = function(index) {
console.log(index, 'index removing');
$scope.zipCodes.splice(index, 1);
}
});
There can be multiple zipControllers
in one builderController
inside of the builder controller I want to come up with an object or way to iterate through all of the Zip Controllers so that I can calculate a total distance and number of zip codes used, each time one of the child controllers is updated. 在构建器控制器内部的一个builderController
可以有multiple zipControllers
,我想提出一个对象或方法来遍历所有Zip控制器,以便每次使用以下一种方法时,我都能计算出总距离和所用邮政编码的数量。子控制器已更新。
What is the most efficient way to do something like this in Angular? 在Angular中最有效的方法是什么?
BASIC GOAL 基本目标
So there could be 4-5 zipController
elements in one builderController
I want to have a variable in the builderController
called something like totalZipCodes
which counts the total number of zip codes in each zipCodes
array for each controller, How would I do that with a service or factory? 所以有可能是4-5 zipController
在一个元素builderController
我想有一个变量在builderController
称为像totalZipCodes
其计算在每个邮政编码总数zipCodes
阵列的每个控制器,我会怎么做,与服务或厂? Or is there another way? 还是有另一种方法?
将数据存储在工厂中,然后让控制器致电工厂进行计算。
As @PrinayPanday suggested in his comment, you should use something like a component/directive to do this. 正如@PrinayPanday在他的评论中建议的那样,您应该使用类似组件/指令的方法来执行此操作。 I'm prefacing this by saying I will be using the term directive and component interchangeably as I'm not sure of your constraints. 首先,我不确定是否会受到约束,因此我将交替使用术语“指令”和“组件”。 I would achieve this by doing the following: 我可以通过执行以下操作来实现:
You could also use the child's scope to declare a callback on some event (such as $onInit
) rather than defining the directive controllers. 您还可以使用子级的作用域在某些事件(例如$onInit
)上声明回调,而不用定义指令控制器。 I have answered several questions like this. 我已经回答了几个这样的问题。 So you might find these answers to be helpful in understanding the above solution more: 因此,您可能会发现以下答案有助于进一步了解上述解决方案:
As I'm rereading your question, I have to ask if there may not be a better way to solve this by sharing the data in a service/model rather than needing custom directives? 当我重新阅读您的问题时,我不得不问是否有更好的方法可以通过在服务/模型中共享数据而不是自定义指令来解决此问题?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.