Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

AngularJS newbie here.... I have a basic framework of an app located here:

http://plnkr.co/edit/HlQvMKF735YrBL2tOYGf?p=preview

The app contains an app.js and a couple of sub-models/controllers.

app.js:

var app = angular.module('MyApp', ["ngRoute","page1","page2"]);

app.config(['$routeProvider', function ($routeProvider) {

    //$routeProvider.otherwise({redirectTo: '/page1/'});  // this works just fine if uncommented

}]);

app.controller('MainCtrl', function($scope) {   // none of this works

    $scope.pageTitle = "Page Title";  //
    $scope.myName = 'Scott';

    $scope.hideSessionInfo = true;
    $scope.toggleSessionData = function() {
        console.log('toggleSessionData');
        $scope.hideSessionInfo = !$scope.hideSessionInfo;
    };
});

I want there to be a top-level controller to handle states of items outside of the ng-view. (i.e. showing/hiding some server session info)

I can't get this outer-level controller to work. The controllers on the routes work just fine.

I know I'm doing something fundamentally wrong, but I can't figure it out.

Updated

Fixed by adding the ng-controller onto the body and giving it my global controller name.

Thanks, Scott

share|improve this question
 
Where are you declaring this controller? Usually you should be fine if you asign ng-controller to an element above ng-view. Also it would be good not post static links, as those might change, but a fiddle or plunker or the like. –  hugo der hungrige yesterday

1 Answer

up vote 0 down vote accepted
<div ng-controller ="MainCtrl">
    <div ng-view></div>
</div>

Should usually work. You need to attach your controllers via a directive (here ng-controller and ng-view, which switches the controller depending on the route).

share|improve this answer
 
I was thinking that if I named my app (i.e. ng-app="MyApp"), then I wouldn't have to explicitly mention ng-controller anywhere. Is this not true? –  Scott yesterday
 
This is not true no. Imagine if all of your controllers would be loaded by default, that would be an incredible mess, when it comes to scopes, as they prototypically inherit from each other downwards the dom. Usually controllers are attached to a specific dom-node. Here via ng-controller or ng-view, but also directives can have controllers. –  hugo der hungrige yesterday
 
Great, thanks!! –  Scott yesterday

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.