Вопрос

I would like to remove the # hash from URLs using Angularjs' $locationProvider.html5Mode(true).

Example: The address bar displays http://localhost/shop instead of http://localhost/#/shop.

Everything works well untill I refresh a page. If i refresh, the following Laravel Route (defined in routes.php) is accesed

Route::resource('shop', 'ShoppingController')

not the AngularJS Route (defined in app.js)

$routeProvider.when('/shop', { 
    templateUrl: 'templates/shop.html', 
    controller: 'ShoppingController' 
});

My Code:

routes.php (Laravel Routes)

Route::get('/', function() {
    return View::make('index'); 
});
Route::resource('shop', 'ShoppingController'); 

app.js (AngularJS Routes)

var app = angular.module('shoppingApp',['ngRoute','SharedServices']); 

app.config(function($routeProvider, $locationProvider) { 
    $routeProvider.when('/shop', {
        templateUrl: 'templates/shop.html', 
        controller: 'ShoppingController'
    });
    $routeProvider.otherwise({ redirectTo: '/' }); 
    $locationProvider.html5Mode(true); 
});

My directory structure:

Project
    /app 
        /...
        /views
            -index.php (single page application file)
            -routes.php (Laravel routes)
    /public
        /...
        /js
            -angular.js
            -app.js
        -index.php (Laravel index file)

Tried Solutions:

Rewrite the htaccess file so that all requests are redirected to index.php (the single page application file, from where AngularJS would take over the routing). Problem: In this way the Laravel route (Route::resource('shop', 'ShoppingController'); - necessary for interaction with the database) becomes inaccessible to the AngularJS $http service:

app.js

app.controller("ShoppingController", function($scope, $http) {
    $http.get('/shop', { cache: true}).
        success(function(data, status) {
        $scope.items = data
    }).
    error(function(data, status) {
        console.log('Status: ' + status);
        });
});

Question: How can I solve the routing problem, so that the AngularJS route, not the Laravel Route gets accessed if I refresh localhost/shop?

Это было полезно?

Решение

From what I read, it seems like Laravel is reading the modified route when you refresh the page. In this case, you should make Laravel continue to make the original view even if it would otherwise be a 404 redirect.

Try adding the following somewhere on the Laravel side (Ex. routes.php)

App::missing(function($exception)
{
    return View::make('index');
});

Note: You might want to have AngularJS's routing use .otherwise to handle pages that are not found.

Другие советы

A better solution is to redirect this way:

'Redirect::to('/#/' . Request::path())'

When you refresh or go to the URI directly:

  • 'Request::path()': returns the requested URI i.e. ('/shop/categories/electronics');
  • AngularJS in 'html5Mode' still responds to the '#/' prefix;
  • If angular detects the prefix when in HTML5 mode it will remove the prefix for you.

Final solution:

App::missing(function($exception) {
    return Redirect::to('/#/' . Request::path());
});

If you are using Laravel 5 then go to app/Exception/Handler.php and place the code below:

public function render($request, Exception $e)
{
    if($e instanceof NotFoundHttpException)
    {
        return Redirect::to('/#/' . Request::path());
    }
    return parent::render($request, $e);
}

If you wana have more than one single page application running in html5mode or just have another use for App::missing inside a Laravel app you migh use a rewrite rule like this:

#Redirect base url of AngularJS app in html5mode

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} ^/path/.+$
RewriteRule  ^(path)/(.*)  /path/#/$2           [R=301,L,NE]

I have another solution which I found quite useful. Rather than just making home page view, I pass in the URI to the home page, which will get checked by a controller and redirect accordingly (the Angular way). This means that if you are on myapp.com/about and you refresh, instead of taking you home, it takes you back to the page you were currently on.

routes.php: Notice that I have a URI wildcard that I pass in as an argument to the callback function, then as a variable to the view.

// Note that this must be on the bottom of your routes file because
// if you have any registered route with a similar pattern
// it will get caught by this route and never reach any registered routes you might have
Route::get('{slug}', function($slug){
    return View::make('index', compact('slug'));
});


// These routes will never get hit, so move them above Route::get('{slug}')
Route::get('about', function(){...});
Route::get('contact', function(){...});

index.blade.php:

<html ng-app"myApp">
<head>
    ...
</head>
<body>
    <!--Check if there is a variable named $slug that is set-->
    <!--If it is, set hidden input with ng-model-->
    @if(isset($slug))
        <input type="hidden" value="{{slug}}" ng-model="slug" ng-controller="RedirectController">
    @endif

    <div ng-view></div>
</body>
</html>

app.js

angular.module('myApp', [])
    .controller('RedirectController', ['$location', '$scope', function ($location, $scope) {
        // If slug is set, redirect to that slug
        if ($scope.slug) {
            $location.path('/' + $scope.slug);
        }
    }]);

For Laravel 4.x or 5.x i use this simple and nice trick and there is no need to change .htaccess file. this trick is very simple and works for me. it doesn't redirect URL and user will stay on same URL when refresh page and page will refresh:

Route::get('dashboard/{all?}', function(){
    return view('main.index');
});

here my dashboard app is my SPA. this way we can resolve 404 errors pages too.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top