Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 工厂提供的角度访问模块范围_Javascript_Angularjs_Angularjs Scope - Fatal编程技术网

Javascript 工厂提供的角度访问模块范围

Javascript 工厂提供的角度访问模块范围,javascript,angularjs,angularjs-scope,Javascript,Angularjs,Angularjs Scope,我是个新手 我想要的是,当从外部调用工厂方法时,该方法应该更新模块范围数据,如下所示: fileList.controller('FileListController', ['$scope', function ($scope) { $scope.device = {}; $scope.files = []; $scope.isDeviceDefined = function () { return typeof $scope.device === 'ob

我是个新手

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

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

$scope
从技术上讲是控制器本地的,即不提供角度服务;视图子系统将其提供给它实例化的每个控制器。因此,服务不能将作用域注入到它们。而且他们不应该这样做,从概念上讲,让服务层依赖于视图是错误的。你能做什么?(1) 让服务返回一个对象并将其绑定到作用域(2)将作用域作为参数[(3)可能是其他参数]传递给服务方法。我会选择(1)。作用域是由/for指令创建的。控制器与指令相关联,这就是为什么可以授予它们访问其作用域的权限。服务与指令没有连接。因此,它们与作用域无关。那么,当调用deviceFiles工厂方法时,我怎么可能更新$scope值呢?