Angularjs传递对象指令 [英] Angularjs passing object to directive

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

问题描述

下面角新手。我试图找出什么错误,而通过对象的指令。

Angular newbie here. I am trying to figure out what's going wrong while passing objects to directives.

这是我的指令:

app.directive('walkmap', function() { 
  return {
    restrict: 'A',
    transclude: true,
    scope: { walks: '=walkmap' },
    template: '<div id="map_canvas"></div>',
    link: function(scope, element, attrs)
    {
      console.log(scope);
      console.log(scope.walks);
    }
  };
});

这就是我所说的指令模板:

and this is the template where I call the directive:

<div walkmap="store.walks"></div>

store.walks 是对象的数组。

当我运行此, scope.walks 日志,未定义,而范围罚款记录作为一个范围,甚至有一个孩子的一切,我要寻找的数据。

When I run this, scope.walks logs as undefined while scope logs fine as an Scope and even has a walks child with all the data that I am looking for.

我不知道我在做什么错在这里,因为这个确切的方法工作previously我。

I am not sure what I am doing wrong here because this exact method has worked previously for me.

编辑:

我已经创建了所有必需的code一plunker: http://plnkr.co/edit/uJCxrG

I've created a plunker with all the required code: http://plnkr.co/edit/uJCxrG

正如你所看到的 {{}散步} 是范围可用,但我需要访问它的连接功能,其中它仍然记录为未定义。

As you can see the {{walks}} is available in the scope but I need to access it in the link function where it is still logging as undefined.

推荐答案

由于您使用的 $资源来获取你的数据,该指令的链接功能数据之前运行可用(因为 $资源的结果是异步的),所以第一次在链接功能 scope.walks 将是空/未定义。因为你的指令模板包含 {{}} S,角度设置了一个 $观看散步,所以当 $资源填充数据时, $观看触发器和显示更新。这也解释了为什么你看到在控制台中散步的数据 - 的时候,你点击链接范围扩大,将数据填充

Since you are using $resource to obtain your data, the directive's link function is running before the data is available (because the results from $resource are asynchronous), so the first time in the link function scope.walks will be empty/undefined. Since your directive template contains {{}}s, Angular sets up a $watch on walks, so when the $resource populates the data, the $watch triggers and the display updates. This also explains why you see the walks data in the console -- by the time you click the link to expand the scope, the data is populated.

要解决您的问题,在您的链接功能 $观看来知道什么时候该数据是可用的:

To solve your issue, in your link function $watch to know when the data is available:

scope.$watch('walks', function(walks) {
   console.log(scope.walks, walks);
})

在生产code,只是警惕它被未定义:

In your production code, just guard against it being undefined:

scope.$watch('walks', function(walks) {
  if(walks) { ... }
})

更新:如果您正在使用一个版本棱角分明,其中 $资源支持的承诺,也见@ sawe的答案

Update: If you are using a version of Angular where $resource supports promises, see also @sawe's answer.

这篇关于Angularjs传递对象指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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