我试图从浏览器中的 URL 向 Controller 传递一个参数,例如,122 应该在 $scope.id
中传递 Controller ,所以加载的 JSON 是这个 http://52.41.65.211:8028/api/v1/categories/122/books.json
,但不起作用,知道吗?
网址示例 http://www.example.com/categories/122
app.js
...
.when('/categories/:categoryId', {
controller: 'BookCategoryController',
templateUrl: 'views/booksincategory.html'
})
...
控制者
app.controller('BookCategoryController', ['$scope', 'bookcategories', '$routeParams', function($scope, bookcategories, $routeParams) {
bookcategories.getAllBooks($scope.id).then(function(response) {
$scope.detail = response.data.books[$routeParams.categoryId];
});
}]);
服务
app.service('bookcategories', ['$http', function($http) {
return {
getAllBooks: function(id) {
return $http.get('http://52.41.65.211:8028/api/v1/categories/'+ id + '/books.json')
}
}
}]);
booksincategory.html
<div class="category col" ng-repeat="book in detail">
<h3 class="title">{{book.title}}</h3>
</div>
最佳答案
如果您的 URL 是 http://www.example.com/categories/122
并且路由参数是这样的
.when('/categories/:categoryId', {
controller: 'BookCategoryController',
templateUrl: 'views/booksincategory.html'
})
然后你会在 Controller 中得到 categoryId
作为 $routeParams.categoryId
只需设置$scope.id = $routeParams.categoryId;
只需在调用服务之前在您的 Controller 中进行设置即可。所以你的 Controller 会像
app.controller('BookCategoryController', ['$scope', 'bookcategories', '$routeParams', function($scope, bookcategories, $routeParams) {
$scope.id = $routeParams.categoryId;
bookcategories.getAllBooks($scope.id).then(function(response) {
$scope.detail = response.data.books;
});
}]);
就用
$scope.detail = response.data.books;
无需使用 $scope.detail = response.data.books[$routeParams.categoryId];它的语法不正确。希望这对你有用。您在 Controller 中错误地分配了 $scope.detail 。我看不到 HTML 中的任何问题
关于javascript - 将参数从 URL 传递给 $scope.id - angularJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46220672/