我有我的base.html:
<div ng-controller=NavCtrl>
<nav>
<a ng-click="getWork(work)" ng-repeat='work in works'>{{$index+1}}</a>
</nav>
</div>
我的路由器:
.config(function($routeProvider) {
$routeProvider
.when('/ardiye/:workNo', {
controller:'DetailCtrl',
templateUrl:'/static/web/js/api/templates/detail.html'
});
})
我的控制者:
.controller('NavCtrl', function($scope, $location, $http) {
$scope.works = [];
$http({method: 'GET', url: '/api/v1/work'}). //collects all works
success(function(data, status, headers, config) {
$scope.works = data.objects;
});
// Trying to pass the selected work to new view, how?
$scope.getWork = function(work) {
$scope.selectedWork=work;
$location.path('/ardiye/'+work.id+'/') };
})
.controller('DetailCtrl', function($scope) {
// here i have to get the selectedWork, how?
})
detail.html:
<h1>{{selectedWork.title}}</h1>
导航控制器发送作品列表。然后,当单击链接时,我想通过路由器将工作对象发送到新的详细控制器(以便不进行另一个服务器调用)。
但是当点击链接时“getWork”&#39;函数无法调用,我无法将工作对象发送到细节控制器。我怎样才能做到这一点?
答案 0 :(得分:1)
在控制器之间共享数据的最常用方法是使用服务。在这种特殊情况下,这个简单的代码应该可以工作:
app.config(['$routeProvider', function($routeProvider){
$routeProvider
.when('/ardiye', {templateUrl: 'page1.html', controller: 'View1Ctrl'})
.when('/ardiye/:id', {templateUrl: 'page2.html', controller: 'View2Ctrl'})
.otherwise({redirectTo: '/ardiye'})
}]);
app.factory('WorkService', [function(){
var WorkService = {};
WorkService.data = { SOMEIDFORITEM1: {id: "SOMEIDFORITEM1", content: "some content"}, SOMEIDFORITEM2: {id: "SOMEIDFORITEM2", content: "some content"}};
WorkService.someMethod = function(){}; //in case you also need to share logic
return WorkService;
}]);
app.controller('View1Ctrl'. ['$scope', 'WorkService', function($scope, WorkService){
$scope.workService = WorkService;
$scope.works = $scope.workService.data;
}]);
app.controller('View2Ctrl'. ['$scope', '$routeParams', 'WorkService', function($scope, $routeParams, WorkService){
$scope.workService = WorkService;
$scope.currentWork = $scope.workService.data[$routeParams.id];
}]);
干杯
答案 1 :(得分:0)
在您的控制器中包含$ location服务,一旦您有工作对象,只需致电
$location.path('ardiye/'+id);
您试图在关注链接之前调用该函数,但这不起作用。