2

I am trying to access parent controller scope from a directive function. When I try to get the value of $scope.$parent it returns me the object. But when I try to access any variable from that object it returns Undefined.

app.controller('myCtrl', function ($scope, $http, $timeout) {

    $scope.init = function(){

        $http.get('url.php').success(function(data){
            $scope.assignmentInfo = data.record;
        });

    };
});


app.directive('getInfo', [function(){
    return {
        restrict: 'A',
        scope:{
            data:'=',
            title: '='
        },
        link:function(scope, elem, attrs){
            scope.$watch('data.visible', function(val){
                // do something

            });
        },
        controller: function($scope) {
            console.log($scope.$parent); // return an object

            console.log($scope.$parent.assignmentInfo); // return undefined


        },
        templateUrl: 'template.html'
    };
}]);

First console.log($scope.$parent) return the following output: enter image description here

But $scope.$parent.assignmentInfo return underfined

How do I access the assignmentInfo?

2
  • try this way : jsfiddle.net/wZrjQ/1 Commented Mar 21, 2018 at 4:56
  • not what im trying to do Commented Mar 21, 2018 at 7:29

1 Answer 1

6

It is caused, by fact, that you try to print assignmentInfo, when it is not yet assigned, so you should $watch for it:

angular.module('app', [])
.controller('ctrl', ['$scope', '$timeout', function($scope, $timeout) {
    $timeout(function() {
      $scope.assignmentInfo = 'some data';
    }, 1000)
}])
 .directive('myDirective', function() {
    return {
      scope: {},
      template: '<div>from directive: {{assignmentInfo}}</div>',
      controller: function($scope) {      
        $scope.$watch(function() {
          return $scope.$parent.assignmentInfo;
        }, function(value) {
          if (value){
            console.log(value);
            $scope.assignmentInfo = value;
          }
        })
      }
    }
})
<script src="//code.angularjs.org/snapshot/angular.min.js"></script>

<div ng-app='app' ng-controller='ctrl'>    
  <my-directive></my-directive>
</div>

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

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.