【发布时间】:2016-12-15 11:49:25
【问题描述】:
您好,我正在尝试在 angularjs 中显示简单的组件,其中孩子需要访问父名称。我的代码如下所示:
HTML 文件:
<html>
<head>
<script type='text/javascript' src='angular.min-1.5.0.js'></script>
<script type='text/javascript' src='app.js'></script>
</head>
<body ng-app="componentApp">
<div ng-controller="helloCnt">
<hello name="Parent"></hello>
<hello1 name="Child"></hello1>
<label>List: <input name="namesInput" ng-model="names" ng-list=" | " required></label>
</div>
</body>
</html>
代码:
app.component('hello', {
transclude: true,
template:'<p>Hello I am {{$ctrl.name}} and ctrl name is {{myName}}</p>',
bindings: { name: '@' },
controller: function($scope) {
$scope.myName = 'Alain';
alert(1);
}
});
app.component('hello1', {
require: {
parent: 'hello'
},
template:'<p>Hello I am {{$ctrl.name}} && my parent is {{myNameFromParent}} </p>',
bindings: { name: '@' },
controller: function($scope) {
$scope.myNameFromParent=this.parent.myName;
alert(2);
}
});
它会抛出一个错误:
TypeError: Cannot read property 'myName' of undefined
我无法弄清楚代码中有什么问题以及为什么它找不到父级。关于我所犯错误的任何输入。似乎是我可能错过的一个小错误。
【问题讨论】:
-
hello 和 hello1 是同级作用域,检查一下!
-
我认为您的组件结构有问题。组件应该对父组件一无所知。这是组件设计的最佳实践。
标签: angularjs components angular-components