Adam Modlin
Adam Modlin

Reputation: 3024

Pass parameters to controller in defined route?

Say I have an app defined as such:

angular.module('myApp', ['myControllers'])
    .config(['$routeProvider', function($routeProvider) {
        $routeProvider.when('/', {
            templateUrl: 'myTemplate.html',
            controller: 'MyController'
            //???
        })]);

How can I say, set $scope.myVariable via this route definition? I want to use this for breadcrumbs.

Upvotes: 0

Views: 183

Answers (2)

lbrazier
lbrazier

Reputation: 2654

I think a better way to do what you are doing is to use route parameters. See https://docs.angularjs.org/api/ngRoute/service/$routeParams

You can make your route something like /Chapter/:chapterId

and in your controller, inject $routeParams and access the value like so: $routeParams.chapterId

Upvotes: 2

Adam Modlin
Adam Modlin

Reputation: 3024

Turns out you can use the resolve property in the .when method like so:

.when('/', {
    templateUrl: 'myTemplate.html',
    controller: 'MyController',
    resolve: {
        test: function() {return "test";}
    }
});

Then in my controller I don't access it via the $scope but I inject it like so:

.controller('MyController', ['$scope', 'test', function($scope, test) {
    //test contains "test"
}]);

Upvotes: 0

Related Questions