Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS: Unable to access scope from within directive

model.data contains the following:

{
    "name": "Jamie",
    "age": 25
}  

I have a directive that looks like:

<my-directive data="model.data"></my-directive>  

I have defined the directive as follows:

app.directive('myDirective', function(){  
    return {
        restrict: 'E',
        scope: {
            data: '='
        },
        templateUrl: 'grid.html',
        controller: function($scope) {
            console.log($scope);
            console.log($scope.data);
        }
    }
}

Problem is that console.log($scope) returns the value in $scope. I can see it containing data:

{
    $$asyncQueue: Array[0],
    $$childHead: null,
    ...
    ...
    data: Array[1]
}

However, console.log($scope.data) returns undefined. Any clue why?

like image 294
user109187 Avatar asked Jan 15 '23 00:01

user109187


1 Answers

Anytime something like console.log($scope); works, but console.log($scope.someProperty); doesn't, it is because someProperty is being set as a result of resolving a promise (such as an $http call or a promise created with $q).

The first log appears to work, when what is actually happening is that by the time you manually look at the log entry (i.e., click to expand its contents), the value has been populated/resolved.

In your controller, you'll need to $watch the property, and set up the watch callback function to do whatever it is you want to do with the data once it arrives/is resolved.

like image 139
Mark Rajcok Avatar answered Jan 20 '23 03:01

Mark Rajcok