AngularJS从范围指令获取价值 [英] AngularJS directive get value from scope

查看:141
本文介绍了AngularJS从范围指令获取价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过我的范围,对象,以我的指令,并能正常工作! GET请求后,我更新我的属性称为项目范围。这包含像标题,内容等一些值...如果我登录这一切工作正常,但是当我尝试登录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从范围指令获取价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆