plumby101
plumby101

Reputation: 133

Pass variables into controller from route in Angular

I am trying to use Angular routes to control the view. As well as set the template and controller I want to pass in a variable into the controller so that it loads in the appropriate JSON content.

Here is my current route code...

 app.config(['$routeProvider',
   function ($routeProvider) {
       $routeProvider.
         when('/forum/:forumID', {
             templateUrl: '/AngularTemplates/forumListing.html',
             controller: 'forumViewFullList'
         }).
         when('/thread/:threadID', {
             templateUrl: '/AngularTemplates/thread.html',
             controller: 'forumThread'
         }).
         otherwise({
             templateUrl: 'blah',
             controller: 'blah'
         }
            
         );
   }]);

and this is the controller, not the variable at the end of the HTTP request...

app.controller('forumViewFullList', function ($scope, $http, $timeout) {

     function loadSell() {
         $http.get("/umbraco/api/openzone/GetMessages?pageSize=50&pageNumber=1&forumId="+forumID)
         .then(function (response) {

            /// do something

         });
     }

     loadSell();
 })

How do I retrieve the forumID from the route and pass it into the controller?

Thanks

Upvotes: 0

Views: 1545

Answers (2)

danday74
danday74

Reputation: 57036

i would switch to using angular ui.router which is the de facto solution. much better than the default angular routing.

with ui router you can attach data to state objects ...

https://github.com/angular-ui/ui-router/wiki#attach-custom-data-to-state-objects

.state('contacts.list', {
    templateUrl: 'contacts.list.html',
       data: {
         customData1: 44,
         customData2: "red"
     } 
  })

you can even attach functions to a state which return data on resolution ...

https://github.com/angular-ui/ui-router/wiki#resolve

Upvotes: 0

Dane Macaulay
Dane Macaulay

Reputation: 814

// Given:
// URL: http://server.com/index.html#/Chapter/1/Section/2?search=moby
// Route: /Chapter/:chapterId/Section/:sectionId
//
// Then
$routeParams ==> {chapterId:'1', sectionId:'2', search:'moby'}

See angular docs for $routeParams

Upvotes: 2

Related Questions