0

I don't know very much about angular, and I'm trying to get the hang of best practices regarding the use of URL routing and states and whatnot. I've got a scenario. It's a simple question, but I'm using it to get a handle on what's available to me.

Say that I have two completely separate web pages for displaying information on Ford cars and Toyota cars. When you access the pages, all you have is the car ID number, so you just hit the url "cars.com/info/id:198273918273". What's the best way, using angular.js, to immediately strip the id number from the url, use it to look up the car make, and display the appropriate html page, all without changing the url displayed at the top of the browser?

2
  • are you using ngRoutes or angular-ui router? Commented Jan 21, 2015 at 17:55
  • I'm trying to work with stateProvider, so ui router Commented Jan 21, 2015 at 18:02

2 Answers 2

1

you can use functions in your route templateUrl

.when('/your_url/:car_id', {
    templateUrl: function(attrs){ 
        //Example of the login yours will be complex i guess :P
        if(attrs.car_id == 1) { return 'template_ford.html' }
        if(attrs.car_id == 2) { return 'template_toyota.html' }
    },
    controller  : 'someController'
})

and by that your template can be chaged before the page is rendered and no need to send the user to a different url

Sign up to request clarification or add additional context in comments.

1 Comment

Just a little modification to the answer: He probably has his templates named by the id: templateUrl: function(attrs){ return attrs.id + ".tpl.html"; }
0

Assuming that you are using angular-ui router

$stateProvider
.state('car-get', {
  url:'/info/{car_id}/', 
  controller: ['$scope','$stateParams',function($scope,$stateParams){
       var car_id = $stateParams.car_id;
       // now you can get your car info 
       // and bind it to your template.
       $scope.car = myservice.getcarinfo(car_id) //Here goes your service or your api calls to get car info 
  }], 
  templateUrl: 'path_to_detail_car_page.html',
});

Here is a good begginer tutorial for Angular-ui Router

1 Comment

But in this case, am I not just binding the data from different makes to the same template? It may sound contrived, but imagine that the Ford and Toyota display pages have different layouts, so that I need two different templates ("ford.html" and a "toyota.html"). Can I dynamically assign one of these two template URL's to the car-get state?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.