Search code examples
javascriptangularjsangularjs-directiverestangular

Angular directive isolate scope to parent binding undefined


I'm using (the awesome) Restangular and i'm running into something that forces me to use scope.$parent (not awesome), and i don't want to use that. It seems even though my controller is the parent scope to my directive's scope, the = isolated scope binding is evaluated before my parent controller is executed.

With the following HTML:

<div ng-controller="myController">
    <div x-my-directive x-some-value="parentValue"></div>
</div>

And the following directive:

myApp.directive("myDirective", function () {
    return {
        restrict: 'A',
        link: function (scope, elem) {
            console.log(scope.someValue); // Logs 'undefined' :(
        },
        scope: {
            someValue: "="
        }
    }
});

And the following controller:

myApp.controller("myController", function($scope, allMyValues) {
    allMyValues.getList().then(function(parentValue){
        $scope.parentValue = parentValue;
    });
}

As shown in my directives link function, evaluating a scope property that should have been bound to my parent's scope property returns undefined. However when i change my directives link function to the following:

    myApp.directive("myDirective", function () {
        return {
            restrict: 'A',
            link: function (scope, elem) {
               setTimeout(function() {
                  console.log(scope.someValue); // Logs '{1: number_1, 2: number_2}'
                }, 2000);
            },
            scope: {
                someValue: "="
            }
        }
    });

How do i go about resolving this??

Thanks


Solution

  • that should helps:

    myApp.controller("myController", function($scope, allMyValues) {
    //add this line
    $scope.parentValue={};
    
        allMyValues.getList().then(function(parentValue){
            $scope.parentValue = parentValue;
        });
    }
    

    $scope.parentValue not exist until your request is resolved so add line like below to your code sample demo http://jsbin.com/komikitado/1/edit