问题
I am trying to navigate to another page by using the selected objectID. Angular Routing,
var myApp = angular.module('myApp', ['ngRoute']);
myApp.config(function($routeProvider){
$routeProvider.when('/',{
controller: 'BooksController',
templateUrl: 'views/books.html'
})
.when('/books/details/:id',{
controller: 'BooksController',
templateUrl: 'views/book_details.html'
})
});
Angular Controller:
var myApp = angular.module('myApp');
myApp.controller('BooksController', ['$scope', '$http', '$location', '$routeParams', function($scope, $http, $location, $routeParams){
console.log('BooksController loaded...');
// This To get request all the books: it works fine
$scope.getBooks = function(){
$http.get('/api/books').then(function(response){
$scope.books = response.data;
});
}
// This to get request a book with specific id it works fine
$scope.getBook = function(){
var id = $routeParams.id;
$http.get('/api/books/'+id).then(function(response){
$scope.book = response.data;
});
}
}]);
And then I have this html page which work also fine accept the button in the page, this button supposed to give me a clean templateUrl to navigate to another html page but it give me weird URL:
<div class="panel panel-default" ng-init="getBooks()">
<div class="panel-heading">
<h3 class="panel-title">Latest Books</h3>
</div>
<div class="panel-body">
<div class="row">
<div ng-repeat="book in books">
<div class="col-md-6">
<div class="col-md-6">
<h4>{{book.title}}</h4>
<p>{{book.description}}</p>
<a class="btn btn-primary" href="#/books/details/{{book._id}}">View Details</a>
</div>
<div class="col-md-6">
<img class="thumbnail" src="{{book.image_url}}">
</div>
</div>
</div>
</div>
</div>
And once I press the button I'm supposed to get a clean url such as: http://localhost:3000/#!/books/details/599701c1f3da51117535b9ab but instead I get this url! http://localhost:3000/#!/#%2Fbooks%2Fdetails%2F599701c1f3da51117535b9ab
回答1:
Seems like you have hashprefix !
, then your URL should also have !
after hash(#
)
href="#!/books/details/{{book._id}}"
Since Angular 1.6 hashprefix
is defaulted to !
, you can disable this behavior by setting hashPrefix
to ''
(blank).
.config(['$locationProvider',
function($locationProvider) {
$locationProvider.hashPrefix('');
}
]);
回答2:
Its because your url is getting converted into codes. %2f means a /.
You need to have this configuration to avoid this behavior of angular
myApp.config(['$locationProvider', function($locationProvider) {
$locationProvider.hashPrefix('');
}]);
回答3:
You have Prefix in url which is converting into character i.e url encoding.
So you need to fix $locationProvider's hashPrefix
property by replacing its value with empty/blank string
$locationProvider.hashPrefix('');
来源:https://stackoverflow.com/questions/45800718/angular-giving-a-weird-templateurl