abhaygarg12493
abhaygarg12493

Reputation: 1605

Correct Way to do Routing with ID in AngularJS

I am learning AngularJS . Now I am confuse in routing with AngularJS . Actually I need at my main page that Task is created.http://localhost:8080/#/ .So this url is for creation of Task .Now if user wants to edit the task then I append the id in routeParams http://localhost:8080/#/5 in this way . Now if user wants to see allTask then the URL is http://localhost:8080/#/allTask . But it takes allTask as a id and go to edit task URL . routing for this is

'use strict';

angular.module("mainApp",['ngRoute','ngResource','ngGrid','ui.codemirror']).
config(['$routeProvider', function($routeProvider) {
    $routeProvider
    .when('/:id', {
    templateUrl: 'component/task/Task.html',
    controller: 'taskController'
    })
    .when('/', {
    templateUrl: 'component/task/Task.html',
    controller: 'taskController'
    })

    .when('/allTask', {
        templateUrl: 'component/allTask/allTask.html',
        controller: 'allTaskController'
    })  
}])

Upvotes: 0

Views: 1525

Answers (1)

Karlen Kishmiryan
Karlen Kishmiryan

Reputation: 7522

Move your allTask route before the one with :id, like this:

'use strict';

angular.module("mainApp", ['ngRoute', 'ngResource', 'ngGrid', 'ui.codemirror']).
config(['$routeProvider',
  function($routeProvider) {
    $routeProvider
      .when('/allTask', {
        templateUrl: 'component/allTask/allTask.html',
        controller: 'allTaskController'
      })
      .when('/:id', {
        templateUrl: 'component/task/Task.html',
        controller: 'taskController'
      })
      .when('/', {
        templateUrl: 'component/task/Task.html',
        controller: 'taskController'
      });
  }
])

Also you can have one route instead of the latter two, by making the parameter :id optional (with question mark ?). Here is the updated code:

'use strict';

angular.module("mainApp", ['ngRoute', 'ngResource', 'ngGrid', 'ui.codemirror']).
config(['$routeProvider',
  function($routeProvider) {
    $routeProvider
      .when('/allTask', {
        templateUrl: 'component/allTask/allTask.html',
        controller: 'allTaskController'
      })
      .when('/:id?', {
        templateUrl: 'component/task/Task.html',
        controller: 'taskController'
      });
  }
])

Upvotes: 1

Related Questions