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>
-
you can't create nested controller like this... But you can inject one into another.Sankar– Sankar2017年07月20日 09:42:26 +00:00Commented Jul 20, 2017 at 9:42
-
Could you please kindly help me with a code snippet to inject a controller in another controller @SankarRajAshok Bala– Ashok Bala2017年07月20日 10:31:24 +00:00Commented Jul 20, 2017 at 10:31
3 Answers 3
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);
});
Comments
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);
})
Comments
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
.