5

我有一个典型的 CRUD 应用程序,其中包含用于列表视图和详细视图的单独路由和控制器。

列表的数据是使用$resource.

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

相反,由于在我的列表控制器中我已经有了我正在编辑的项目,我想将此项目从列表控制器传递到细节控制器。

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

请帮忙。

4

1 回答 1

4

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

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

或者我前段时间写的一个小提琴: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;
    });
}
于 2012-10-23T15:55:14.177 回答