简体   繁体   中英

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

Looks like you are waiting for a promise to resolve before assigning the value to the scope.

There are a few ways you might handle this.

One way is to try moving the Restangular call to a resolve function for the view which holds the controller. Then you get access to the resolved data directly as an injection in your controllers

Another way might be to just assign the promise directly to the scope and then in the linking function wait for a resolution.

scope.someValue.then(function(value) { console.log(value); });

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM