(据我所知)有两种普遍接受的方法来处理这个问题。第一种、最流行、也是最强烈推荐的方法是使用服务或工厂。另一种是使用router和routeParams将卡的ID传递给细节控制器。
我不知道你打算如何显示你的详细信息页面(使用路由器导航到新页面,或者简单地隐藏/显示一些隐藏的 DOM 元素的指令),但是服务/工厂可以在这两种情况下使用,其中,routeParams 只能在其中使用。
(我还强烈建议您尽可能严格地遵循此处的角度风格指南:https://github.com/johnpapa/angular-styleguide/blob/master/a1/README.md https://github.com/johnpapa/angular-styleguide/blob/master/a1/README.md如果你想避免很多头痛)
angular.module('ngApp', [])
.service('CarDetailService', CarDetailService)
.controller('task', taskData)
.controller('carDetails', carDetails);
CarDetailService.$inject = ['$http', 'API'];
function CarDetailService($http, API) {
var CarDetailService = this;
CarDetailService.setCar = function(carId) {
CarDetailService.carId = carId;
};
CarDetailService.getCar = function() {
return $http.get(API + "/car/" + CarDetailService.carId);
};
}
taskData.$inject = ['$scope', '$http', 'API', 'CarDetailService'];
function taskData($scope, $http, API, CarDetailService) {
$http.get( API + '/tasks' ).
success(function(data) {
$scope.mainTask = data;
console.log(data);
});
$scope.selectCar = function(carId) {
CarDetailService.setCar(carId);
$location.url('/car-details-route'); //go to details page
};
}
carDetails.$inject = ['$scope', 'CarDetailService'];
function carDetails($scope, CarDetailService) {
CarDetailService.getCar().success(function(details) {
$scope.details = details;
});
}
和你的ng-repeat
看起来像这样:
<div ng-repeat="task in mainTask.tasks" ng-click="selectCar(task['Car ID'])">
{{task['Car ID']}}
</div>
该服务是单例,这意味着 id 将在路由更改和控制器存在时持续存在。
另一种方法是使用 $routeParams。相关文档在这里:https://docs.angularjs.org/api/ngRoute/service/ https://docs.angularjs.org/api/ngRoute/service/$routeParams
$routeParams 允许您将 ID 添加到路由器读取并传递给控制器的路径中:
angular.module('ngApp', []).config(function($routeProvider) {
$routeProvider.when('/car-details-route/:carId', {
controller: 'carDetails',
templateUrl: 'car-details.html'
});
})
.controller('task', taskData)
.controller('carDetails', carDetails);
taskData.$inject = ['$scope', '$location'];
function taskData($scope, $location) {
$http.get( API + '/tasks' ).
success(function(data) {
$scope.mainTask = data;
console.log(data);
});
$scope.selectCar = function(carId) {
$location.path('/car-details-route/'+carId);
};
}
carDetails.$inject = ['$scope', 'API', '$routeParams'];
function carDetails($scope, API, $routeParams) {
$http.get(API + "/cars/" + $routeParams.carId).success(function(details) {
$scope.details = details;
});
}