问题描述
我正在将我的范围对象传递给我的指令,这很好用!在获取请求后,我使用名为 project 的属性更新我的范围.这包含一些值,如标题、内容等......如果我记录这个一切正常,但是当我尝试记录 scope.project 时,我收到未定义的消息,但是当我记录范围时,我会在 JSON 树中看到项目对象... 这里会发生什么?
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('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
}
}
}]);
模板:
<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);
});
非常感谢
推荐答案
你在做一些异步的事情,console.log 不会等待 http.get 正在做的任何异步任务,或者当它返回时,因此,控制台日志在更改项目值之前执行,因此它给出未定义.向您正在使用的 $http 方法添加一个回调,然后执行该 console.log,或者在请求完成时发送一个包含您想要完成的所有内容的回调.一周前我遇到了这个问题,问题是我的 console.log 在异步方法设置变量之前被执行.例如,在控制器上使用您的 http.get 请求,只需添加 console.log.
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);
});
这篇关于AngularJS 指令从作用域中获取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!