javascript - 如何在不同的 ngRoute 页面中使用相同的控制器
问题描述
嗨,我想要不同页面中的相同控制器。如何将对象传递到不同的页面。下面是我的示例代码。
Page1.html
<body ng-app="myapp" ng-controller="studentController">
<div>
<table border="0">
<tr>
<td>
<table>
<tr>
<th>Name</th>.
<th>Marks</th>
</tr>
<tr ng-repeat="subject in student.subjects">
<td> <a href="#Page2">{{ subject.name }}</a></td>
<td>{{ subject.marks }}</td>
</tr>
</table>
</td>
</tr>
</table>
</div>
<div ng-view></div>
</body>
脚本.js
var app = angular.module("myapp", ["ngRoute"]);
app.config(function ($routeProvider) {
$routeProvider
.when("/Page1", {
template: '<h1>Page 1</h1>'
})
.when("/Page2", {
templateUrl: 'Page2.html',
controller: 'studentController'
})
.otherwise({
template: '<h1>note found</h1>'
})
});
app.controller('studentController', function ($scope) {
$scope.student = {
firstName: "AAA",
lastName: "ZZZ",
fees: 500,
subjects: [
{ name: 'Physics', marks: 70 },
{ name: 'Chemistry', marks: 80 },
{ name: 'Math', marks: 65 },
{ name: 'English', marks: 75 },
{ name: 'Computers', marks: 67 }
],
};
});
Page2.html
<body ng-app="myapp" ng-controller="studentController">
<h1>Hello</h1>
<h2>
subject name - {{ subject.name }}
</h2>
</body>
如何将主题对象从第 1 页传递到第 2 页。
我在路由配置中定义了相同的控制器。
我有什么需要定义的吗?
解决方案
如何将主题对象从第 1 页传递到第 2 页。
而不是传递对象,而是传递一个索引。
在以下 URL 中使用索引ng-repeat
:
<tr ng-repeat="subject in student.subjects">
<td> <a href="#Page2/{{$index}}">{{ subject.name }}</a></td>
<td>{{ subject.marks }}</td>
</tr>
使用索引参数定义路由:
.when("/Page2/:index", {
templateUrl: 'Page2.html',
controller: 'subjectController'
})
主体控制人
.controller('SubjectController', function($scope, $routeParams) {
$scope.params = $routeParams;
$scope.subject = $scope.subjects[$routeParams.index];
})
Page2.html
<div>
<h1>Subject index {{params.index}}</h1>
<h2>
subject name - {{ subject.name }}
</h2>
</div>
元素中的ng-view
控制器将从主应用程序中实例化的控制器继承数据。
推荐阅读
- java - Okhttp在代理连接关闭后发送http请求
- mongodb - MongoDB:删除位置
- android - 如何使用 WorkManager 在 MVVM 中定期更新来自 Retrofit 的数据?
- python - 如何训练 tensorflow deeplab 模型?
- python - python print double Bracket "{{}}" 使用 .format 就可以了
- python - 行和列中具有相同变量的交叉表
- python - Zelle-graphics 窗口——克隆对象而不是移动
- c# - 从数据库的列中获取数据列表,具体取决于另一列中的数据
- python - 创建按钮类时出现递归错误
- python - 每次我在 Django 中调用视图时,如何防止加载我的 Keras 模型?