angular 从工厂访问模块范围

angular access module scope from factory

我是 angular 的新手。

我想要的是当从外部调用工厂方法时,该方法应该更新模块范围数据,如下所示:

fileList.controller('FileListController', ['$scope', function ($scope) {
    $scope.device = {};
    $scope.files = [];
    $scope.isDeviceDefined = function () {
        return typeof $scope.device === 'object' && $scope.device !== null && $scope.device.hasOwnProperty('label');
    };
}]);

fileList.factory('deviceFiles', ['$scope', 'files', function ($scope, files) {
    return {
        setFilesForDevice: function (device) {
            $scope.device = device;
            $scope.files = files.getFilesFromDevice(device.label);
        }
    };
}]);

但是它说 $scope 是一个未知的提供者。还有其他方法可以更新模块数据吗? setFilesForDevice 是一种通过单击不同控制器模板内的按钮调用的方法。

你需要在这里采取一些不同的方法。首先,您通过 $routeParams.device.

在控制器中获取您的设备 ID

然后您创建一个可注入到 FileListController 中并传递有关文件的信息的服务,即

fileList.controller('FileListController', ['$scope', '$routeParams', 'deviceFilesService', function ($scope, $routeParams, deviceFilesService) {
    $scope.device = $routeParams.device;
    $scope.files = deviceFilesService.getFilesForDevice($routeParams.device);
}]);

fileList.service('deviceFilesService', ['files', function (files) {
    this.getFilesForDevice = function (device) {
        // Code to look up list of files the the device
    };
}]);