简体   繁体   中英

How to make a 'top-level'-controller in angular-js?

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. (ie 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

<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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM