3
这似乎是一个非常简单的问题,但我还没有得到它的答案很长一段时间。问题是,当你有一个组件层次结构时,你如何将数据从父组件传递到子组件,以便孩子们能够访问其范围内的数据(或其他变量?)如何将数据从父组件发送到AngularJs中的子组件
我是使用AngularJs 1.5.5
这里是我现在所做的工作,我已经在JavaScript代码中添加了关于我真正想实现的内容的评论。 - https://plnkr.co/edit/blY85rvARIqkmfCnRBOV?p=preview
的index.html
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.5/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<div ng-app="myApp">
<dependency></dependency>
</div>
</body>
</html>
的script.js
// Code goes here
angular.module('myApp', ['dependency']);
// this is parent component
angular.
module('dependency', ['dependency2']).
component('dependency', {
templateUrl: 'dependency.html',
controller: ['$scope', function dependencyController($scope) {
$scope.dependencyScopedVariable = "Some local variables of dependency";
$scope.childComponentParams = [{ name: "child1"}, { name: "child2"}];
}]
});
// this is child component
angular.
module('dependency2', []).
component('dependency2', {
templateUrl: 'dependency2.html',
controller: ['$scope', function dependency2Controller($scope) {
// How to access childParam from parent here?
$scope.itemGotFromParent = "this should be from parent";
}]
});
dependency.html
<div>{{dependencyScopedVariable}}</div>
<dependency2 ng-repeat="childParam in childComponentParams"></dependency2>
dependency2.html
<!-- How to get the childParam repeated in ng-repeat here? -->
<div>{{itemGotFromParent}}</div>
好的,这看起来像是解决方案之一。两个问题: 1)'传递数据作为范围变量'或'需要父组件的控制器'是两种方法相同吗? 2)在这里,每个孩子都可以访问整个'childComponentParams'数组。我们不能将这个数组的一个元素传递给基于索引的每个孩子吗? –
当我提到'将数据作为范围变量传递'时,让我纠正自己,我的意思是使用'bindings'作为'component'调用的角度。其次,两种方法都不同,我已经添加了示例#2来演示这种技术。我可以通过巧妙地使用'ng-if'来传递个人元素。 – Gaurav
另外一件事,当使用'require'时,你可以访问控制器实例本身,并且通过它你可以访问该控制器的'this'对象上的任何东西。 – Gaurav