mateusz-c
mateusz-c

Reputation: 110

Angular template pages

I want to have template site in AngularJs with /example/car/id where in different ids is a page for different cars . In app.js i wrote :

angular
  .module('carApp', [
    'ngCookies',
    'ngResource',
    'ngRoute',
  ])
  .config(function ($routeProvider) {
    $routeProvider
      .when('/', {
        templateUrl: 'views/main.html',
        controller: 'MainCtrl'
      })
      .when('/car/:id', {
        templateUrl: 'views/car.html',
        controller: 'CarCtrl'
      })
  });

In Json i made 2 cars:

[{
"model": "Audi",
"year": "1999"
}
{
"model": "BMW",
"year": "2005"
}]

In car.js

angular.module('carApp')
.controller('CarCtrl',  ['$scope','$http', function($scope, $http)
{    
    $http.get('scripts/controllers/cars.json').success (function(data){
    $scope.cars = data;
});

}]
);

Where and what code I need to write to have templates where in example/car/1 will show details about Audi and example/car/2 will show details about BMW ?

Upvotes: 0

Views: 114

Answers (3)

mateusz-c
mateusz-c

Reputation: 110

I've changed the CarCrl to look like this :

angular.module('motoApp')
.controller('CarCtrl',  ['$scope','$http', '$routeParams', function($scope, $http,
        $routeParams) {    
    $http.get('scripts/controllers/cars.json').success (function(data){
        $scope.car = data[$routeParams.id];
    });

}]
);

And changed the JSON to dictionary :

{
"1": {
    "model": "Audi",
    "year": "2012",

"2": {
    "model": "BMW",
    "year": "2012",
}
}

and that is what i wanted to achive. Now in html i have :

<p>{{ car.model }}</p>
<p>{{ car.year }}</p>

and when i visit /car/1 it shows details about Audi and in /car/2 there is BMW

Upvotes: 0

krs8785
krs8785

Reputation: 1147

Assuming you would have some sort of table or list displaying the car for the user to select you could have something like

 <div ng-controller="carCtrl">
    <ul ng-repeat = "car in cars">
       <li> <a href ="#/cars/{{car.model}}> {{car.model}} </a></li>
    </ul>        
 </div>

So this will create a list of cars that the user can select. On clicking on the link it will go to page on that model. (Note I am not using id here because you dont have id in you json)

Upvotes: 1

Amr Elgarhy
Amr Elgarhy

Reputation: 68902

You can read the param using $routeParams and put them as a query string to your URL or use this version on $http :

$http({
    url: user.details_path, 
    method: "GET",
    params: {user_id: user.id}
 });

https://stackoverflow.com/a/13760360/20126

Upvotes: 1

Related Questions