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?

DarkLeafyGreen
  • 69,338
  • 131
  • 383
  • 601

2 Answers2

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.

Supr
  • 18,572
  • 3
  • 31
  • 36
  • I want to simply show the length of tickets in parent scope. That's all. What solution would you suggest? – DarkLeafyGreen May 06 '13 at 08:40
  • 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. – Supr May 06 '13 at 09:00
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

Community
  • 1
  • 1
luksch
  • 11,497
  • 6
  • 38
  • 53