1

I have an index page wherein I define two controllers. I want to call one main controller always (should be rendered always) and the other is called only for specific sub URL calls. Should I make one nested within another, or I can keep them independent of each other? I don't have access to change routes or anything, only the controller. Right now when I use the template (HTML) mentioned, it calls/renders both controllers, even though url is say /index

Only for /index/subPage, I want both controllers to be rendering. 

/index
/index/subPage

HTML:

<div ng-controller="MainCtl" ng-init=initMain()>        
    <p> Within ctller2 {{results}} </p>
</div>


<div ng-controller="Ctller2">       <!-- should not be displayed unless /subPage/mainUrl is rendering -->
    <p> Within ctller2 {{results}} </p>
</div>

JS:

app.controller('MainCtl', ['$scope', '$http', '$location', function ($scope, $http, $location) {

    $http.get('xx/mainUrl').then(function(data) {
        $scope.results = someDataJSON;
        console.log(someDataJSON);
    });

    $scope.initMain = function() {      
            $scope.initMethods();   
    }   
}]); 


app.controller('Ctller2', ['$scope', '$http', '$location', function ($scope, $http, $location) {
 // This controller gets initialized/rendered/called even when xx/mainUrl is called, and when xx/subPage/mainUrl is called too.. 
    $http.get('xx/subPage/mainUrl').then(function(data) {
        $scope.results = someDataJSON;
        console.log(someDataJSON);
    })

    $http.get('xx/subPage').then(function(data) {
        $scope.results = data.data;
        console.log(data);
    })

   angular.element(document).ready(function () {
     alert('Hello from SubCtl, moving over from main controller to here');
    });


}]);

What am I doing wrong? I'm new to Angular.js

Loser Coder
  • 2,338
  • 8
  • 42
  • 66

1 Answers1

2

You can conditionally initiate a controller using ng-if. So you could try something like this:

<body ng-controller="MainCtrl">

    <div ng-controller="ctrl1">{{hello}}</div>
    <div ng-controller="ctrl2" ng-if="showCtrl2">{{hello}}</div>

</body>

and then set the value of the variable in a parent controller by checking the current url using $location.path()

var app = angular.module('plunker', []);

app.config(function($locationProvider){
    $locationProvider.html5Mode(true); 
});

app.controller('MainCtrl', function($scope, $location) {
  $scope.showCtrl2 = ($location.path() === 'my path');
});

app.controller('ctrl1', function($scope){
  $scope.hello = 'ctrl1 says hello';
});

app.controller('ctrl2', function($scope){
  $scope.hello = 'ctrl2 says hello';
});

But it's a bit hacky and for a larger project a more robust solution would require using something like ui.router.

Matt Herbstritt
  • 4,754
  • 4
  • 25
  • 31