Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm passing my scope object to my directive and this works fine! After a get request I update my scope with a property called project. This contains some values like title, content, etc... If I log this everything is working fine but when I try to log scope.project I get the message undefined, but when I log scope I see the project object in the JSON tree... What can happens here?

All console logs show the correct information but I can't access it...

directive:

.directive('project', ['$http', function ($http) {
    return {
        restrict: 'AEC',
        link: function (scope, element, attrs) {
            console.log(scope); // gives perfect json object including the project object
            console.log(scope.project.content); // gives undefined
        }
    }
}]);    

template:

<div showcontent id="createdcontent"></div>

controller: (This is where I set the scope)

$http.get ('/api/projects/' + id)
    .success (function (data) {
        $scope.project = data.project;
    })
    .error (function (data){
        console.log("error: " + data);
    }); 

Many thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
182 views
Welcome To Ask or Share your Answers For Others

1 Answer

You are doing something asynchronously, and the console.log wont wait for whatever asynchronous task http.get is doing, or when it returns, thus, the console log is being executed before the value of project is changed so it gives undefined. Add a callback to the $http method you are using and then do that console.log, or send a callback with everything you want done when the request is finished. I had this issue a week ago and the problem was that my console.log was getting executed before the variable had been set by the asynchronous method. For example, using your http.get request on the controller, just add the console.log.

$http.get ('/api/projects/' + id)
    .success (function (data) {
        $scope.project = data.project;
        console.log(scope.project.content);
    })
    .error (function (data){
        console.log("error: " + data);
    }); 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...