0

I would like to create a controller inside a controller in angular Js. But my code is not working. Please help me on this.

Controller :

app.controller('MainController',function($rootScope,$scope){
 console.log('MainController Created');
 $scope.test = "Success";
 app.controller('InnerController',function($scope){
 console.log('Inside the InnerController');
 console.log($scope.test);
 })
});

below is my html body:

<body>
 <div ng-app="myApp" ng-controller="MainController">
 Enter your Name :
 <input type="text" ng-model="name" placeholder="your name">
 <div ng-show="name">
 <h2>This is called Two way binding :: {{name}}</h2>
 </div>
 <div ng-controller="InnerController">
 <h2>{{name}}</h2>
 </div>
 </div>
</body>
asked Jul 20, 2017 at 9:37
2
  • you can't create nested controller like this... But you can inject one into another. Commented Jul 20, 2017 at 9:42
  • Could you please kindly help me with a code snippet to inject a controller in another controller @SankarRaj Commented Jul 20, 2017 at 10:31

3 Answers 3

1

You should put your inner controller declaration outside of MainController, because they both need to be initialised before html is parsed

app.controller('MainController',function($rootScope,$scope){
 console.log('MainController Created');
 $scope.test = "Success";
});
app.controller('InnerController',function($scope){
 console.log('Inside the InnerController');
 console.log($scope.test);
});
answered Jul 20, 2017 at 9:41

Comments

1

in html like you did main is a father controller of innercontroller but in angular it is controller with himself like that:

app.controller('MainController',function($rootScope,$scope){
 console.log('MainController Created');
 $scope.test = "Success";
});
 app.controller('InnerController',function($scope){
 console.log('Inside the InnerController');
 console.laog($scope.test);
 })
answered Jul 20, 2017 at 9:43

Comments

0

You cannot create a controller inside another controller. But you can nest DOM elements with different controllers inside each other. So you should change your controllers' declaration to this:

app.controller('MainController',function($rootScope,$scope){
 console.log('MainController Created');
 $scope.test = "Success";
});
app.controller('InnerController',function($scope){
 console.log('Inside the InnerController');
 console.log($scope.test);
});

Pay attention that test is still available in the InnerController.

answered Jul 20, 2017 at 9:41

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.