问题描述
这里是 Angular 新手.我试图找出将对象传递给指令时出了什么问题.
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
记录为 undefined
而 scope
记录为 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.
我不确定我在这里做错了什么,因为这个确切的方法以前对我有用.
I am not sure what I am doing wrong here because this exact method has worked previously for me.
我已经用所有必需的代码创建了一个 plunker:http://plnkr.co/edit/uJCxrG
I've created a plunker with all the required code: http://plnkr.co/edit/uJCxrG
如您所见,{{walks}}
在范围内可用,但我需要在链接函数中访问它,但它仍然记录为未定义.
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.
推荐答案
由于您使用 $resource
获取数据,因此指令的链接函数在数据可用之前运行(因为结果from $resource
是异步的),所以在链接函数 scope.walks
中的第一次将是空的/未定义的.由于您的指令模板包含 {{}}
s,Angular 在 walks
上设置了一个 $watch
,所以当 $resource
填充数据,$watch
触发器和显示更新.这也解释了为什么您会在控制台中看到步行数据 - 当您单击链接以扩展范围时,数据已填充.
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.
要解决您的问题,请在您的链接函数 $watch
中了解数据何时可用:
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);
})
在您的生产代码中,请注意防止未定义:
In your production code, just guard against it being undefined:
scope.$watch('walks', function(walks) {
if(walks) { ... }
})
更新:如果您使用的是 $resource
支持承诺的 Angular 版本,另请参阅@sawe 的回答.
Update: If you are using a version of Angular where $resource
supports promises, see also @sawe's answer.
这篇关于Angularjs 将对象传递给指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!