javascript - 将参数从 URL 传递给 $scope.id - angularJS

标签 javascript html angularjs

我试图从浏览器中的 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/

相关文章:

javascript - 如果按钮位于 Canvas 顶部并且鼠标进入按钮,如何防止 Canvas 触发 mouseenter/mouseleave 事件

javascript - 带有 GYP "exceptions"的 Node.js 附加组件

javascript - 根据对象的数量将每个 JSON 对象及其项目放入 <li> 中

javascript - Angular-modal-service 不显示模态

javascript - AngularJS 中的非模态/无模式对话框,无需使用 jquery-ui

javascript - 在继续之前等待图像加载

javascript - 如何根据事件导航选项卡动态生成页面标题?

javascript - 当网格 API bool 值为 === 'true' 时更改 CSS

html - 如何对齐汉堡包菜单项?

AngularJS/UI ui-sortable 没有隔离范围?