将数据从列表视图传递到angular.js中的详细视图

时间:2022-05-18 04:30:55

I have a typical CRUD app with separate routes and controllers for the list view as well as the detail views.

我有一个典型的CRUD应用程序,它有单独的路径和控制器用于列表视图以及详细视图。

The data for the list is retrieved using a $resource.

使用$ resource检索列表的数据。

Currently in my detail view controller I fetch the item from the server using the $resource which results in an extra http request.

目前在我的详细视图控制器中,我使用$ resource从服务器获取项目,这导致额外的http请求。

Instead, since in my list controller I already have the item that I am editing, I would like to pass this item from the list controller to the detail controller.

相反,因为在我的列表控制器中我已经有我正在编辑的项目,我想将此项目从列表控制器传递给详细控制器。

But I do not know how. I can make one single controller for both views but this does not seem right.

但是我不知道怎么做。我可以为两个视图制作一个控制器,但这似乎不对。

Please help.

1 个解决方案

#1


4  

You can use a service to share data between controllers:

您可以使用服务在控制器之间共享数据:

exemple: https://groups.google.com/d/msg/angular/IjKY_CRyRno/kP0M_LTzOTkJ

or a fiddle I wrote some time ago: http://jsfiddle.net/XqDxG/169/

或者我前段时间写过的小提琴:http://jsfiddle.net/XqDxG/169/

myModule.factory('mySharedService', function($rootScope) {
    var sharedService = {};
    sharedService.data = {};
    sharedService.data.message = '';

    return sharedService;
});

function ControllerZero($scope, sharedService) {
    // expose service data to angular scope
    $scope.sharedData = sharedService.data;

    $scope.handleClick = function(msg) {
        sharedService.data.message = msg;            
    };

    $scope.$watch('sharedData.message', function(msg) {
        $scope.message = msg;
    });
}

function ControllerOne($scope, sharedService) {
    $scope.sharedData = sharedService.data;

    $scope.$watch('sharedData.message', function() {
        $scope.message = 'ONE: ' + sharedService.data.message;
    });
}

#1


4  

You can use a service to share data between controllers:

您可以使用服务在控制器之间共享数据:

exemple: https://groups.google.com/d/msg/angular/IjKY_CRyRno/kP0M_LTzOTkJ

or a fiddle I wrote some time ago: http://jsfiddle.net/XqDxG/169/

或者我前段时间写过的小提琴:http://jsfiddle.net/XqDxG/169/

myModule.factory('mySharedService', function($rootScope) {
    var sharedService = {};
    sharedService.data = {};
    sharedService.data.message = '';

    return sharedService;
});

function ControllerZero($scope, sharedService) {
    // expose service data to angular scope
    $scope.sharedData = sharedService.data;

    $scope.handleClick = function(msg) {
        sharedService.data.message = msg;            
    };

    $scope.$watch('sharedData.message', function(msg) {
        $scope.message = msg;
    });
}

function ControllerOne($scope, sharedService) {
    $scope.sharedData = sharedService.data;

    $scope.$watch('sharedData.message', function() {
        $scope.message = 'ONE: ' + sharedService.data.message;
    });
}