Amb*_*gar 10 components angularjs angular-components
嗨,我想在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>
Run Code Online (Sandbox Code Playgroud)
码:
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);
}
});
Run Code Online (Sandbox Code Playgroud)
它会抛出一个错误:
TypeError:无法读取undefined的属性'myName'
我无法弄清楚代码中出了什么问题以及为什么它找不到父母.对我犯的错误有任何意见.看起来我可能错过了一个小问题.
实际上,在对@gyc 指出的答案进行以下修改后,我得到了答案:
JS代码:
angular
.module('componentApp', [])
.controller('helloCtrl', function ($scope) {
$scope.names = ['morpheus', 'neo', 'trinity'];
})
.component('hello', {
transclude: true,
template: '<p>Hello I am {{parentCtrl.name}} and my name is {{parentCtrl.myName}}</p><ng-transclude></ng-transclude>',
controllerAs: 'parentCtrl',
controller: function ($scope) {
this.myName = 'Braid';
},
bindings: {
name: '@'
}
})
.component('hello1', {
template: '<p>Hello I am {{$ctrl.name}} && my parent is {{myNameFromParent}} </p>',
controller: function ($scope) {
this.$onInit = function () {
$scope.myNameFromParent = this.parent.myName;
};
},
bindings: {
name: '@'
},
require: {
parent: '^hello'
}
});
Run Code Online (Sandbox Code Playgroud)
HTML:
<html>
<body ng-app="componentApp">
<div ng-controller="helloCtrl">
<hello name="Parent">
<hello1 name="Child"></hello1>
</hello>
<label>List:
<input name="namesInput" ng-model="names" ng-list=" | " required>
</label>
</div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
我这样做的常见错误是没有遵循嵌套组件格式,也没有在我的父级中使用 transclude。当我进行这两个更改并修改我的后续代码时,其余部分工作正常。
PS - HTML 中包含的 ng-list 与组件无关。那是出于其他目的。
@gyc - 感谢您的帮助。您的意见有所帮助。
@daan.desmedt - 我希望在组件而不是指令中找到解决方案。
使用 require 继承,需要嵌套组件:
<hello name="Parent"></hello>
<hello1 name="Child"></hello1>
Run Code Online (Sandbox Code Playgroud)
而是做
<hello name="Parent">
<hello1 name="Child"></hello1>
</hello>
Run Code Online (Sandbox Code Playgroud)
然后你可以像这样要求父母:
require: {
parent: '^^hello'
},
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
14062 次 |
最近记录: |