Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/385.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 从URL-angularJS向$scope.id传递参数_Javascript_Html_Angularjs - Fatal编程技术网

Javascript 从URL-angularJS向$scope.id传递参数

Javascript 从URL-angularJS向$scope.id传递参数,javascript,html,angularjs,Javascript,Html,Angularjs,我正在尝试将一个参数从浏览器中的URL传递到控制器,例如,122应该在控制器中的$scope.id中传递,因此加载的JSON就是这个http://52.41.65.211:8028/api/v1/categories/122/books.json,但不起作用,知道吗 URL示例 app.js ... .when('/categories/:categoryId', { controller: 'BookCategoryController',

我正在尝试将一个参数从浏览器中的URL传递到控制器,例如,122应该在控制器中的
$scope.id
中传递,因此加载的JSON就是这个
http://52.41.65.211:8028/api/v1/categories/122/books.json
,但不起作用,知道吗

URL示例

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>

{{book.title}}

如果您的URL是
http://www.example.com/categories/122
和路由参数如下

.when('/categories/:categoryId', {
    controller: 'BookCategoryController',
    templateUrl: 'views/booksincategory.html'
})
然后,您将在控制器中以
$routeParams.categoryId

只需设置
$scope.id=$routeParams.categoryId

在调用服务之前,只需在控制器中进行设置。所以你的控制器会像

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];这是一个错误的语法。希望这对你有用。您在控制器中错误地分配了$scope.detail。我在HTML中看不到任何问题

你有机会看一下吗?我不明白你为什么要提出多个问题。。而是将注意力集中在单个代码上,并在一个地方进行修复:)有意义,但仍然没有显示任何内容,它现在似乎正确地调用了JSON,我的HTML中是否有错误?@user1937021 use$scope.detail=response.data.books;您使用了错误的语法。希望这对你有用。