将数据传递给 AngularJS 中的自定义指令 [英] Passing data to a custom directive in AngularJS

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

问题描述

我有一个页面,其中显示了一堆使用 http 检索的图像缩略图.我使用 ng-repeat 遍历数组并生成 html.
这工作正常.

我还创建了一个自定义指令,将其作为属性绑定到由 ng-repeat 生成的 img 元素.
这也很好用.

然而,当我尝试将数据传递到我的自定义指令的范围时,它就会崩溃.数据绑定失败,ng-repeat 不会替换图像的 url,所以我最终得到 404,因为 url 无效.就这么多了.

非常感谢任何帮助,因为我是 Angular 的新手.

我的 html 模板:

<div class="row"><div class="col-lg-3 col-md-4 col-sm-4 col-xs-6 col-padding" ng-repeat="gPhotos 中的gImg"><div class="相框"><img src="{{gImg.thumbnailUrl}}" url="{{gImg.imageUrl}}" 图片库>

和我的自定义指令:

myApp.directive('imageGallery',function(){返回 {限制:'A',范围: {网址:'='},控制器:功能($范围){console.log($scope.url);}}

});

解决方案

尝试更改

范围:{网址:'='},

范围:{网址:'@'},

请参阅此处,了解一个非常简单的示例.检查控制台.请参阅此处有什么区别位于 =@ 之间.

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.

I also create a custom directive that I tie as an attribute to img elements generated by ng-repeat.
This also works fine.

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.

Any help is greatly appreciated since I am completely new to Angular.

my html template:

<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>

and my custom directive:

myApp.directive('imageGallery',function(){

return {
    restrict: 'A',
    scope: {
      url: '='
    },
    controller: function($scope){
        console.log($scope.url);
    }
}

});

解决方案

Try changing

scope: {
  url: '='
},

to

scope: {
  url: '@'
},

See here for a very simple example. Check the console. See here what the difference is between = and @.

这篇关于将数据传递给 AngularJS 中的自定义指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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