首页 > 解决方案 > 如何在不同的 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 页。

我在路由配置中定义了相同的控制器。

我有什么需要定义的吗?

标签: javascripthtmlangularjsangularjs-ng-route

解决方案


如何将主题对象从第 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控制器将从主应用程序中实例化的控制器继承数据。


推荐阅读