DontVoteMeDown
DontVoteMeDown

Reputation: 21465

AngularJS Routing infinite loop in spa model with mvc

I have tried a bunch of other posts over the web that seems to be the same problem as mine, but none worked.

I have this menu:

<ul class="nav navbar-nav">
    <li class="active"><a href="#Painel/1">Novas</a></li>
    <li><a href="#Painel/2">Todas</a></li>
    <li><a href="#Painel/3">Finalizadas</a></li>
    <li><a href="#Painel/4">Pendentes</a></li>
</ul>

Quite simple nav bar. This routing setup:

module.config(["$routeProvider", "$locationProvider", function($routeProvider, $locationProvider)
{
    //$locationProvider.html5Mode(true);

    $routeProvider
        .when('/Painel/:painelId/', 
        {
            templateUrl : function(params)
            {
                return "/Painel/Index/" + params.painelId;
            },
            controller  : 'painelController'
        })
        .otherwise(
        {
            redirectTo: "/Painel"
        });
    }]);
}

My MVC Controller:

public class PainelController : Controller
{
    public ActionResult Index(int? id))
    {
        return View();
    }
}

And finally my angular controller:

module.controller('painelController', ["$scope", "$routeParams", function ($scope, $routeParams)
{
    debugger;
}]);

Its a very simple architecture, but angular is looping through its controller infinitely. I took care to set my templateUrl relative with / as many posts suggested over there, but it didn't worked. It works sending the parameter to the mvc Action, but then it starts the loop stopping forever on the angular's controller debugger.

What can I do?

Upvotes: 0

Views: 703

Answers (2)

DontVoteMeDown
DontVoteMeDown

Reputation: 21465

The main problem wasn't on the Angular code, but in the MVC's return Action:

return View();

Since you're working with dynamic content, you don't have to return the full html source(with html, head, body tags...), so I had to change to:

return PartialView();

What makes totally more sense. Because every request was calling a new angular code, that opened a new request and so on... Then I have created two routes for the opitional parameters(I don't know why it doesn't worked as @Tacoman667 pointed)

Upvotes: 0

Tacoman667
Tacoman667

Reputation: 1401

Your problem is that :painelId is not optional and thus you fall into your otherwise() redirect infinitely. Make the :painelId optional like

'/Painel/:painelId?/'

And this should fix your issue. If you are not using a version of Angular that supports optional parameters then you will need to add another when() to cover the '/Painel' route.

Upvotes: 1

Related Questions