How to access parent component in angularjs 1.5
To inherit with require, the components need to be nested:
<hello name="Parent"></hello>
<hello1 name="Child"></hello1>
instead do
<hello name="Parent">
<hello1 name="Child"></hello1>
</hello>
Then you can require the parent like so:
require: {
parent: '^^hello'
},
Actually I got the answer after making following modification with the answer @gyc pointed:
JS CODE:
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'
}
});
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>
The common mistake I was doing it was not following the nested component format and not using transclude in my parent. The rest worked fine when I made these two changes and modified my subsequent code.
P.S - The ng-list included in HTML has nothing to do with components.That was for other purpose.
@gyc - thanks for the help.Your input helped.
@daan.desmedt - I was hoping for the solution in components not directives.