角度访问模块范围从工厂

angular access module scope from factory

本文关键字:工厂 范围 模块 访问      更新时间:2023-09-26

我对角度很陌生。

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

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
    };
}]);