如何使用另一个控制器和视图编辑选定的ng-repeat元素?

时间:2016-06-06 05:42:58

标签: angularjs

我在每个元素前面都有以下带有编辑按钮的元素列表。

查看:

<div ng-controller="studentController" >
        <table>
            <tr ng-repeat="student in controller.students">
                <td>{{student}}</td>
                <td><a href="#/app/student/edit" class="btn btn-default">Edit</a></td>              
            </tr>
        </table>
</div>

studentController:

myApp.controller('studentController', function($http, $scope) {
    var self = this;

    $http.get('students/').then(function(response) {

        self.students = response.data.students;

    });                           
});

当我点击编辑按钮时,我应该可以编辑学生的详细信息,例如其他页面中的成绩和分数。我不确定如何将选定的学生传递到编辑页面。如何使用AngularJS实现这一目标?

1 个答案:

答案 0 :(得分:1)

取决于您使用的路由器,您可以传递params(ui-router):

<ul>
    <li ng-repeat="student in students">
        <a ui-sref="student.detail({ id: student.id })">{{ student.name }}</a>
    </li>
</ul>

您需要一条'student.detail'州的路线

$stateProvider.state('student', {
 template: ...,
 controller: 'studentController'
})


$stateProvider.state('student.detail', {
    url: "/student/:studentId",
    templateUrl: 'student.detail.html',
    controller: function ($stateParams, StudentService) {
        console.log($stateParams.studentId);
        $scope.student = StudentService.get($stateParams.studentId)
    }
})

修改(ngRoute):

myApp.config(function($routeProvider, $httpProvider) { 
  $routeProvider
  .when('/app/student',{ 
      templateUrl : 'app/components/student/student.html', 
      controller: 'studentController', 
  // route for edit student       
  }).when('/app/student/edit/:studentid',{ 
      templateUrl : 'app/components/student/editStudent.html',                        
      controller: 'editStudentControllerCtrl', 
  // route for other      
  }).otherwise('/');

在editStudentControllerCtrl中,您可以通过$ routeParams

访问studentId
controller('editStudentControllerCtrl', function($scope, $routeParams)    
{
 $scope.studentId = $routeParams.studentId;
  // use studentId to fetch and update students
 });

请参阅https://docs.angularjs.org/api/ngRoute/service/$route#example