(AngularJS / ng-route)如何获取模板的输入

(AngularJS / ng-route) How to get inputs for the template?

本文关键字:输入 获取 何获取 AngularJS ng-route      更新时间:2023-09-26

我有一个使用ng-route链接到新视图的index.html文件(例如"index.html/Book/:BookId")。

在 index.html 文件中,我可以看到有关每个项目(例如,每本书)的所有适当信息。在index.js上,我有一个名为routeCtrl的控制器,里面有一个列表,每个book对象都是该列表中的一个项目。

问题:虽然我可以链接到新的ng视图,但我无法弄清楚如何获取每个页面的信息。例如,如果我单击第一页中的"麦克白"链接,我应该在新视图中看到麦克白的信息。

这是我的代码。

索引.html:

<html>
...
<body ng-app="routeApp" ng-controller="routeCtrl">
  <div ng-view></div>
  <div ng-repeat="book in books">
    <h1><a href="Book/{{ book.url }}">{{ book.name }}</a></h1>
  </div>
</body>
</html>

索引.js:

var app = angular.module('routeApp', ['ngRoute']);
app.controller('routeCtrl, function($scope, $route, $routeParams, $location) {
  $scope.$location = $location;
  $scope.$route = $route;
  $scope.$routeParams = $routeParams;
  $scope.books = [
    Atlas Shrugged = { name: "Atlas Shrugged", author: "Ayn Rand", url: "atlas"},
    Neuromancer = { name: "Neuromancer", author: "William Gibson", url: "neuro"}
  ];
});
app.config(function($routeProvider, $locationProvider) {
  $routeProvider
    .when('/Book/:bookId', {
      templateUrl: 'book.html',
      controller: 'routeCtrl',
  })
  $locationProvider.html5Mode(true);
});

书.html(在ng视图中):

<div> // this is the part I don't understand. How do I retrieve each book's information from the object in the JS file?
  <h1>{{ BOOK NAME }}</h1>
  <h3>{{ BOOK AUTHOR }}</h3>
</div>

这里的$scope.books是什么?你会在你的HTML模板中使用它(书籍),但你不能真正迭代这样格式化的列表。

试试这个:

$scope.books = [
  { name: "Atlas Shrugged", author: "Ayn Rand", url: "atlas"},
  { name: "Neuromancer", author: "William Gibson", url: "neuro"}
];

这将在模板中产生一个"books"对象,您可以ng-repeat="book in books"并访问ng-repeat块中的属性,如{{book.name}},就像上面所做的那样。