0

How can I access a property of a controller in a service?

In my case it is an array, which I want to change in my service.

My controller:

myApp.controller('MainController', function ($scope, $interval, externalDataService, AnalyzeService) {
    $scope.myArray = [];
    var size = 10;

    var analyze = function () {
       if($scope.myArray .length > size) {
          AnalyzeService.doSomething();
       }
    };

    var analyzeData = function () {
        externalDataService.getData().then(function (data) {
            $scope.faceReaderData.push(data);
            analyze();
         });
     };

    $interval(analyzeData , 2000);
});

My service:

myApp.service('AnalyzeService', function () {
    this.doSomething = function () {
        //here i want array access
    }
});
3
  • 3
    You can just pass the array into your service function as a parameter. Commented Oct 1, 2015 at 9:45
  • In my case I want make changes in the array, Like delete the first 10 Objects. If I pass the array into the service as a parameter i have to return it and set it as new array. And that´s what i dont want to Commented Oct 1, 2015 at 9:52
  • 1
    Why do you not want to do that? Commented Oct 1, 2015 at 9:58

1 Answer 1

1

You do not want to do that, as it would make your service depend on your controller, which is very undesireable. Instead, add the array as a parameter to your doSomething:

//Appending 1,2,3 to the given array
function doSomething(someArray) {
    return someArray.concat(['1', '2', '3']);
}

This way, your service does not depend on your controller at all, seperating your business logic from your controller.

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.