1

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.

3
  • $scope technically is local to the controller, i.e. there is no Angular service providing it; the view subsystem provides it to each controller it instantiates. So no, services cannot have the scope injected to them. And they shouldn't, conceptually it is wrong to have the service layer depending on the view. What can you do? (1) have the service return an object and bind that to the scope (2) pass the scope to the service method as argument [(3) possibly others]. I would go for (1). Commented Jan 22, 2015 at 12:31
  • Scopes are created by / for directives. Controllers are associated with directives, that's why they can be given access to their scopes. Services have no connection to directives. Ergo they have no business with scopes. Commented Jan 22, 2015 at 12:48
  • Then how could I possibly update the $scope values when the deviceFiles factory method is called? Commented Jan 22, 2015 at 14:05

1 Answer 1

1

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, i.e.

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
    };
}]);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.