Ambar Bhatnagar Ambar Bhatnagar - 3 months ago 44
AngularJS Question

How to access parent component in angularjs 1.5

Hi i am trying to display simple components in angularjs where child needs to access parent name.And my code goes like this:

HTML file:

<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>


CODE:

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);
}
});


And it throws an error :

TypeError: Cannot read property 'myName' of undefined

I am not able to figure out what is wrong in the code and why it can't find the parent.Any inputs on the mistake I am making.Seems to be a small one I might have missed.

gyc gyc
Answer

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'
  },
Comments