2

I have an object that is exposed to $scope and has properties attached to it.

I access this object in my controller and call a service which does little something.

What I need to add to it is new property to the object(which is going to be an array attached to the object as a property) so that updated object is returned to the controller and I can access the elements of this array using data-expression tag{{ }}.

I would like to know in detail about making such manipulations the right way and possible ways of doing it.

1
  • 1
    no different than any other javascript object, what is the specific problem? Commented Jul 12, 2015 at 19:51

1 Answer 1

4

Just add the array to the object.

$scope.myobj = {};

...

// sometime later
var numbers = [1,2,3];
$scope.myobj.numbers = numbers;

EDIT:

To answer your question about scope in a service. Scope is not accessible in a service. Typically you ask your service for something IE data. But your service can do anything, like add 2 numbers, or in your case create an array of something that you need to attach to your object.

module.service('MyService', function() {
    this.add = function(number1, number2) {
      return number1 + number2;
    }

    this.createMyArray = function() {
       // pass in whatever you need to this service in order
       // to create the array you need.

       // example of just returning a hard coded array
       return [1,2,3];
    }
});

Then you can inject your service into your controller which has the scope you want to modify.

app.controller('MyController', function($scope, MyService) {

    $scope.add = function(number1, number2) {
        // Lets use our service to add these numbers and
        // assign result to scope variable
        $scope.answer = MyService.add(number1, number2);
    }

    $scope.myobj = {};
    $scope.makeArray = function() {
        // lets use our service again to create an array
        // this time lets add it to a scope object that already exists.
        $scope.myobj.numbers = MyService.createMyArray();
    }
});

A lot of times services are used to grab/update things from a server, so you will see a lot of examples that make http get/post/put/delete calls. Then from your controller(s) you can use those services to grab data. But again you are not limited to that, your service can simple just hold some static data or helper functions too.

Sign up to request clarification or add additional context in comments.

1 Comment

Is $scope available in service? I am updating it there and returning updated one to controller.

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.