0

I am trying to access a parent scope, but I am getting the error that the scope is undefined.

MyApp.controller('AdminController', function ($scope, $http, $filter, $mdDialog, $window, $location, $mdToast) {

$scope.test = "Test";

}).
controller('ToastCtrl', function($scope, $mdToast, $mdDialog) {
    $scope.openMoreInfo = function(e) {
        if ( isDlgOpen ) return;
        isDlgOpen = true;

        $mdDialog
          .show($mdDialog
            .alert()
            .title($scope.$parent.test)
            .targetEvent(e)
          )
          .then(function() {
              isDlgOpen = false;
          })
    };
}); 

Any suggestion, why I am getting this error.

Thank you in advance.

priya_singh
  • 2,478
  • 1
  • 14
  • 32

2 Answers2

0

You should have posted also your view here (at least), but I assume in your html you have something like this

<div ng-controller="AdminController">
    <div ng-controller="ToastCtrl">
        <!-- openMoreInfo  called somewhere here -->
    </div>
</div>

And you what your controller to look for $scope.test variable in parent scope. You can just try to use angularjs scope inheritance this way

In parent controller change $scope.test = "Test"; with

$scope.Data = {};
$scope.Data.test = "Test";

Then in your child controller use .title($scope.Data.test).
The child controller will try to access $scope.Data object but it doesn't exist in current scope, so it will try to search for it in $parent scope where it can be found.

Naigel
  • 9,086
  • 16
  • 65
  • 106
0

The problem you are not able to access the value is there is no parent-child relationship between your controllers.

You can access it multiple ways:

  1. Either using a service to communicate between controllers.
  2. Using emit/broadcast to communicate
  3. Use $rootscope, but its not recommended.
Thalaivar
  • 23,282
  • 5
  • 60
  • 71