Ambar Bhatnagar Ambar Bhatnagar - 1 year ago 230
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:

<script type='text/javascript' src='angular.min-1.5.0.js'></script>
<script type='text/javascript' src='app.js'></script>
<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>


transclude: true,
template:'<p>Hello I am {{$}} and ctrl name is {{myName}}</p>',
bindings: { name: '@' },
controller: function($scope){
$scope.myName = 'Alain';

require: {
parent: 'hello'
template:'<p>Hello I am {{$}} && my parent is {{myNameFromParent}} </p>',
bindings: { name: '@' },

controller: function($scope){

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 Source

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>

Then you can require the parent like so:

require: {
    parent: '^^hello'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download