Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them; it only takes a minute:

I needed a way to access the parent scope of a controller without having to inject $scope to do so. The reason behind this is that I'm building a SPA and I wanted to apply a class to the body element depending on the current page. I don't want to have to inject $scope into every single one of my controllers just for the sole purpose of changing the class. Also please let me know if I'm looking at this the wrong way, if there is a way to encapsulate this functionality using $routeprovider or a service that is fine too. I've just recently begun to use Angular so I apologize in advance if the solution is really simple, but I was not able to find anything similar to my situation by googling.

Here is the basic setup:

index.html

<body ng-controller="BodyController as body" class="contact-page">
    <nav> ... </nav>
    <main ng-view>
        <div ng-controller="ContactController as contact>
           Contact Page loaded in on click
        </div>
    </main>
</body>

body.controller.js

(function() {
    angular
        .module('app')
        .controller('BodyController', BodyController);

    function BodyController() {
        var body = this;
    }
})();

contact.controller.js

(function() {
    angular
        .module('app')
        .controller('ContactController', ContactController);

    ContactController.$inject = [];

    function ContactController($scope) {
        var vm = this;
    }
})();

app.routes.js

(function () {
    angular
        .module('app')
        .config(routes);

    routes.$inject = ['$routeProvider', '$locationProvider'];

    function routes($routeProvider, $locationProvider) {
        $routeProvider
            .when('/', {
                templateUrl: 'app/home/home.html',
                controller: 'HomeController',
                controllerAs: 'home'
            }).when('/contact', {
                templateUrl: 'app/contact/contact.html',
                controller: 'ContactController',
                controllerAs: 'contact'
            }).otherwise({
                redirectTo: '/'
            });
        $locationProvider.html5Mode(true);
    }

})();
share|improve this question
    
Do you know about service and factory method. This will help you – Jagadeesh Jul 27 at 5:52

Your Answer

 
discard

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

Browse other questions tagged or ask your own question.