0

I have this in main.html:

<div ng-controller="MainCtrl">
 <form ng-controller="SearchCtrl">
  <input ng-model="query" ng-change="changed(query)" />
 </form>
</div>

And, index.html:

<html>
<head>
    <title>Dashboard</title>
</head>
<body ng-app="MyApp">
 <nav ng-controller="NavCtrl">
 ...
 </nav>
 <div ng-view></div>
</body>
</html>

And, my ngRoute config is as follows:

module.config(function($routeProvider)){
 $routeProvider.when('/', {
  templateUrl: 'views/main.html',
  controller: 'SearchCtrl'
 });
}

I tried accessing $scope.$parent in SearchCtrl.js looking for $scope of MainCtrl but I am getting undefined.

I tried changing the controller in my config but then, I am not able to access SearchCtrl. What should I do?

4
  • There shouldn't be a <body> in a route template. Also you would have 2 instances of SearchCtrl with code shown ... one nested inside the other Commented Jan 30, 2016 at 17:05
  • @charlietfl Yeah. So what do I do to make sure I have both controllers nested? Thanks. Commented Jan 31, 2016 at 2:16
  • show the body of your index.html to see your ng-view Commented Jan 31, 2016 at 2:17
  • @charlietfl added the index.html Commented Jan 31, 2016 at 2:21

2 Answers 2

1

Based on structure shown everything inside ng-view will be in controller set by the route config .... SearchCtrl.

Then inside would be MainCtrl and inside that another (new instance) of SearchCtrl

So should probably change route controller to MainCtrl and remove ng-controller="MainCtrl"

module.config(function($routeProvider)){
 $routeProvider.when('/', {
  templateUrl: 'views/main.html',
  controller: 'MainCtrl'
 });
}

main.html

<div>
 <form ng-controller="SearchCtrl">
  <input ng-model="query" ng-change="changed(query)" />
 </form>
</div>
Sign up to request clarification or add additional context in comments.

Comments

1

The main.html already in SearchCtrl scope and you don't need to define the scope again in the view.

Then, defining MainCtrl inside main.html which is under "SearchCtrl" scope will not take MainCtrl as its parent.

Hence remove both controller from main.html

 <form>
 <input ng-model="query" ng-change="changed(query)" />
</form>

Now in index.html, put the MainCtrl as parent to ng-view

.......
<div ng-controller="MainCtrl">
 <div ng-view></div>
</div>
.......

Now try accessing $scope.$parent in your SearchCtrl then you could see it.

1 Comment

But what if I want MainCtrl only for this particular view? Thanks!

Your Answer

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.