AngularJS directive get value from scope

心不动则不痛 提交于 2019-12-13 10:31:56

问题


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:


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);
    }); 


来源:https://stackoverflow.com/questions/27535792/angularjs-directive-get-value-from-scope

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!