mk_yo
mk_yo

Reputation: 770

angularjs and asp.net mvc routing issue

I'm using angularjs inside my asp.net mvc project and have the folowing link in the asp.net view:

<a href="/Organization/Employee/@user.Alias#info">@user.Alias.ToUpper()</a>

that gives me a link like this for example:

http://localhost:53315/Organization/Employee/15#/info

Which I want to be hanled by mvc controller and then use angularjs routing to show template inside returned asp.net view.

Here's my asp.net mvc controller:

      public ActionResult Employee(String id)
        {
          ...
          return View();
        }

routeConfig:

    context.MapRoute(
       "Organization_Employee",
       "Organization/Employee/{id}/{*mod}",
       new { controller = "User", action = "Employee" }
   );

and angularjs stuff:

 $routeProvider
      .when('/info', {
        controller: 'UserCtrl',
        templateUrl: baseTemplateUrl + 'info.html'
    })

    .controller('UserCtrl', ['$scope', '$location', '$routeParams', 'User', function ($scope, $location, $routeParams, User) {
        $scope.user = User.get({ id: $routeParams.id });

How I can get that id('15') parameter from url in angular controller?

Upvotes: 0

Views: 1468

Answers (1)

kolesso
kolesso

Reputation: 336

In your case you can get id by parse window url $window.location.href or $location.absUrl()

.controller('UserCtrl', ['$window', '$location', '$routeParams', 'User', function ($window, $location, $routeParams, User) {
    var splitUrl=$window.location.href.split("#")[0].split("/");
    //or 
    //var splitUrl=$location.absUrl().split("#")[0].split("/");
    var  userId=splitUrl[splitUrl.length]; // some like that
    $scope.user = User.get({ id: userId });

If your url looks like http://localhost:53315/Organization/Employee/#/info/15 or http://localhost:53315/Organization/Employee/15#/info/15

. You can get id that way:

 $routeProvider
  .when('/info/:id', {
    controller: 'UserCtrl',
    templateUrl: baseTemplateUrl + 'info.html'
})

.controller('UserCtrl', ['$scope', '$location', '$routeParams', 'User', function ($scope, $location, $routeParams, User) {
    $scope.user = User.get({ id: $routeParams.id });

This is because $location work with path after hashbang in non HTML5 Mode.

Upvotes: 2

Related Questions