AngularJS -为子指令提供字符串数组
AngularJS - Provide an array of strings to a child directive
我正在Angular中创建一个product gallery指令,它将允许用户使用左/右箭头滚动图像。
什么是最合适的角的方法来饲料我的指令与图像url数组?
你可以假设父控制器已经做了一个API调用来接收这个url数组
。
<div data-ng-controller="MyController as myController">
<my-image-gallery></my-image-gallery>
</div>
我应该在JSON数组中有一个属性吗?比如:
<my-image-gallery images="myController.ImageList"></my-image-gallery>
虽然,我甚至不确定上述是否可能。这意味着JSON必须转换为字符串?
一定有更好的办法
编辑
根据评论,我已经尝试了上面的方法,但我无法从我的控制器内访问"图像"字段。
下面是我在指令中定义的内容:
scope: {
imageSource: '='
},
然后在我的控制器中,我假设我应该能够引用变量imageSource,不是吗?
我觉得你是在用一个奇怪的教程来学习angular。您可以使用MyController as MyController
语法,但这样做的目的是避免使用$scope
。我个人不同意这样做,也不明白为什么人们要这样做。
当您将值附加到$scope
时,它将直接在您的视图中可用(不需要$scope
)。例如,$scope.images
将作为images
传递给您的指令。
要让指令处理该值作为一个变量而不是字符串,它必须使用=
(而不是@
)来定义,你可以在angular指令文档
这是一个如何工作的例子:
Javascript
angular.module('app',[])
.controller('myCtrl',['$scope',function($scope){
$scope.imageList=['img1','img2','img3','img...'];
}])
.directive('myImageGallery',function(){
return {
restrict: 'E',
scope:{
images:'='
},
controller: ['$scope',function($scope){
console.log($scope.images);
}],
replace: true,
template: '<ul><li ng-repeat="img in images">{{img}}</li></ul>'
}
})