2

Fiddle: http://jsfiddle.net/6RBJ5/1/

So basically I want to access an object from parent scope that is modified in child scope.

function Parent($scope) {
    $scope.data = null;
}

function Child($scope) { 
    $scope.data = [{id:1}, {id:2}]
}

HTML:

<div ng-controller="Parent">
  Data length: {{ data.length }}<br>
<div ng-controller="Child"></div>
</div>

However length prints nothing. Any ideas how to fix this?

2 Answers 2

3

One way:

$scope.$parent.data = [{id:1}, {id:2}]

although that doesn't feel right.

Another would be to create the empty array in the parent, and just modify it instead of replacing it in the child.

Or maybe what you really need is to use a service; it depends on what you are really trying to accomplish.

Defining the service:

var myApp = angular.module('myApp', []);
myApp.factory('tickets', function factory() {

    var tickets = [];

    function add(ticket){
        tickets.push(ticket);
    }
    function count(){
        return tickets.length;
    }

    return {
        add: add,
        count: count
    };

});

Using the service:

function Parent($scope, tickets) {
    $scope.tickets = tickets;
}

function Child($scope, tickets) {

    tickets.add({id:1}); 
    tickets.add({id:2});

}

HTML:

<div ng-controller="Parent">
    Data length: {{ tickets.count() }}<br>
    <div ng-controller="Child">       
    </div>
</div>

Notice how clean and business-modelly the controllers are, and that you can extend the tickets concept cleanly in one place and access it from anywhere by injecting it into a controller. You can do this without worrying about the hierarchy or relationship between controllers or polluting your environment. On the other hand it might be overkill if your application is extremely simple.

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

2 Comments

I want to simply show the length of tickets in parent scope. That's all. What solution would you suggest?
Generally the correct way to communicate between between otherwise unrelated controllers is through services, so I think the "right" solution is to use a service. That will keep your controllers decoupled and clean. The downside is that it requires more code. I'll add an example.
1

I think that refers to the question of having globals in angular. the simplest way of doing this is via $rootScope.

see this Global variables in AngularJS

and here

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.