angularjs - Access parent controller data from main controller -


i have following maincontroller:

function maincontroller($scope, dataservice) {    $scope.model = {     data: null   }    $scope.init = function () {     dataservice.getbyid(2)       .success(function (data, status, headers, config) {                  $scope.model.data = data;       })   };    $scope.init();  }  

i have child controller need access parent scope:

function childcontroller($scope) {    $scope.model = {     data: null   }    $scope.init = function () {     #scope.model.data = $scope.$parent.model.data;   };    $scope.init();  }   

i error saying $scope.$parent.model.data null.

if check console $scope.$parent.model.data seems null if click see not , has correct data ...

i believe problem defining data in childcontroller before has been defined in maincontroller due dataservice.getbyid queries database ...

am right?

how can solve this?

you right: problem have, parent controller populates "data" inside promise.

to understand promise is, can check : https://docs.angularjs.org/api/ng/service/$q

when child controller run, promise not have returned yet.

the first way handle adding watch :

function childcontroller($scope) {    $scope.model = {     data: null   }    $scope.init = function () {     //$scope.model.data = $scope.$parent.model.data;    var watchremover = $scope.$watch('$parent.model.data', function(newval, oldval){         if (newval !== oldval && newval !== null){            $scope.model.data = $scope.$parent.model.data;            watchremover();         }    })   };    $scope.init();  }  

another solution handle events :

parent controller :

 dataservice.getbyid(2)   .success(function (data, status, headers, config) {              $scope.model.data = data;      $scope.$broadcast("data loaded");   }); 

child controller :

$scope.$on("data loaded", function(){      $scope.model.data = $scope.$parent.model.data; }); 

Comments

Popular posts from this blog

python - No exponential form of the z-axis in matplotlib-3D-plots -

php - Best Light server (Linux + Web server + Database) for Raspberry Pi -

c# - "Newtonsoft.Json.JsonSerializationException unable to find constructor to use for types" error when deserializing class -