简体   繁体   中英

angular access module scope from factory

I'm pretty new to angular.

What I want is that when a factory method is called from outside, the method should update the modules scope data, like this:

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

But it says, that the $scope is a unknown provider. Is there a other way, that the modules data can be updated? setFilesForDevice is a method that is called by clicking a button inside a different controllers template.

You need to take a bit different approach here. First, you get your device id in the controller via $routeParams.device.

Then you create a service that would be injectable into FileListController and deliver information about files, ie

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM