简体   繁体   中英

Redirection of url angularjs

I'm building an app and i have a little problem.

For the index, i change my url with history.pushstate when i click on a button with jquery. For example, www.mysite.com become www.mysite.com/something without reloading the page. But if a load this page i don't find www.mysite.com because "something" doesn't exist.

And I don't know how do the link between them.

I tried to do this but it doesn't work with AngularJS.

var myApp = angular.module('photo', ['ngRoute']);


myApp.config(['$routeProvider', function($routeProvider) {
    $routeProvider.when('/', {
        templateUrl: 'machin.html'
    });
    $routeProvider.when('/something-one', {
        templateUrl: 'machin.html'
    });
    $routeProvider.when('/something-two', {
        templateUrl: 'machin.html'
    });
    $routeProvider.otherwise({ redirectTo: '/' });
}]);

This is the way to do it or I'm just lost ? ^^


Solved

My solution works sorry all. I forgot the script angular-route but the rest of my script works.

In your button, you can bind event using ng-click instead of using jQuery.

<button ng-click="goto('/something')">Go to something</button>

In your controller:

$scope.goto = function(url) {
   $location.path(url);
}

When you're working with Jquery, you're out of angular scope. So angular will not know about the URL change. You may need to trigger digest cycle in that case.

You could try this

var myApp = angular.module('photo', ['ngRoute']);
myApp.config(['$routeProvider', function($routeProvider) {
    $routeProvider.when('/', {
        templateUrl: 'machin.html'
    })
    .when('/something-one', {
        templateUrl: 'machin.html'
    })
    .when('/something-two', {
        templateUrl: 'machin.html'
    })
    .otherwise({ redirectTo: '/' });
}]);

and in your html

<a href="#/something-one">Go to something one</a>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM