AngularJS directive get value from scope

2019-09-20 17:26发布

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

1条回答
小情绪 Triste *
2楼-- · 2019-09-20 17:54

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);
    }); 
查看更多
登录 后发表回答