将数据传递到AngularJS中的自定义指令 [英] Passing data to a custom directive in AngularJS
问题描述
我有一个页面,显示一堆使用http检索的图像的缩略图.我使用ng-repeat遍历数组并生成html.
效果很好.
I have a page that displays a bunch of thumbnails of images that are retrieved using http. I use ng-repeat to go through the array and generate the html.
This works fine.
我还创建了一个自定义指令,将其作为属性绑定到ng-repeat生成的img元素.
这也很好.
I also create a custom directive that I tie as an attribute to img elements generated by ng-repeat.
This also works fine.
但是,当我尝试将数据传递到自定义指令的范围时,一切都会崩溃.数据绑定失败,ng-repeat不会替换图像的url,所以由于该URL无效,我最终得到了404.尽其所能.
However, when I try to pass data to the scope of my custom directive then it all falls apart. Data binding fails, ng-repeat does not replace the url of the images so I end up getting a 404 since the url is invalid. That is pretty much as far as it goes.
由于我是Angular的新手,因此非常感谢任何帮助.
Any help is greatly appreciated since I am completely new to Angular.
我的html模板:
<div class="portfolioContent">
<div class="row">
<div class="col-lg-3 col-md-4 col-sm-4 col-xs-6 col-padding" ng-repeat="gImg in gPhotos">
<div class="photoframe">
<img src="{{gImg.thumbnailUrl}}" url="{{gImg.imageUrl}}" image-gallery>
</div>
</div>
和我的自定义指令:
myApp.directive('imageGallery',function(){
return {
restrict: 'A',
scope: {
url: '='
},
controller: function($scope){
console.log($scope.url);
}
}
});
推荐答案
尝试更改
scope: {
url: '='
},
到
scope: {
url: '@'
},
有关非常简单的示例,请参见此处.检查控制台.请参见此处有什么区别在=
和@
之间.
See here for a very simple example. Check the console. See here what the difference is between =
and @
.
这篇关于将数据传递到AngularJS中的自定义指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!