SRIKANT MAHARANA
SRIKANT MAHARANA

Reputation: 13

How to access parent controller $scope values in child controller

    var parent = angular.module('parent', ['swxSessionStorage']);

    parent.controller('parent', [

        $scope.idMenu = [{
                label : "id1",
                value : 1
            }]

$scope.name=[abc,def];
     /**
         * Calling child controller
         */

        var childView = $scope.$new(true);
        $controller('child',{$scope:childView});
        $scope.someMetod = function(){
            childView.getChildData();
        }
        }


        --------------
    parent.controller('child', [
    $scope.getChildData = function(){
        $scope.idMenu.value
    }

I'm not able to access parent $scope.idMenu in Child controller?

But Im able to access $scope.name,which is just an array,but Im not able to access JsonArray.

What could be the reason?

Upvotes: 0

Views: 326

Answers (2)

Saurav kr. Agrawal
Saurav kr. Agrawal

Reputation: 119

In parent controller

$scope.$broadcast('event_name', function (){ 
//action on event     
}); 

In child controller

$scope.$on('event_name', function () {   
//data required to pass in parent controller      
});

Upvotes: 1

rrd
rrd

Reputation: 5957

The best way would be to use a service.

app.service('dataService', function() {
  var dataList = [];

  function addData(data) {
    dataList.push(data);
  };

  function getData() {
    return dataList;
  };

  return {
    add: addData,
    get: getData
  };
});

In your parent controller, store the information via the service:

app.controller('parent', function($scope, dataService) {
  $scope.addMyData = function(obj) {
    dataService.addData(obj);
  };
});

And in the child controller, retrieve the information via the service:

app.controller('child', function($scope, dataService) {
  $scope.products = dataService.getData();
});

You cannot inject $scope into the service but you can store data.

Upvotes: 0

Related Questions