Ricky
Ricky

Reputation: 2907

AngularJS - Provide an array of strings to a child directive

I'm creating a product gallery directive in Angular, which will allow the user to scroll through images with left/right arrows.

What is the most appropriate angular approach to feed my directive with the array of image URLs?

You can assume that the parent controller has already made an API call to receive this the array of URLs

E.g.

<div data-ng-controller="MyController as myController">
    <my-image-gallery></my-image-gallery>
</div>

Should I just have an attribute of that takes in the JSON array? Perhaps something like:

<my-image-gallery images="myController.ImageList"></my-image-gallery>

Although, I'm not even sure if the above is possible. It would mean the JSON would have to be converted into a string?

There must be a better way

Edit

As per comments, I've tried the above method, but I can't access the "images" field from within my controller.

Here is what I have defined in my directive:

    scope: {
        imageSource: '='
    },

Then in my controller, I assume I should just be able to reference the variable imageSource, shouldn't I?

Upvotes: 0

Views: 77

Answers (1)

Lenny
Lenny

Reputation: 5939

I think you're using a kinda weird tutorial or something to learn angular. You can use the MyController as MyController syntax, but the goal of that is to avoid using $scope. I personally don't agree with it and don't understand why people would want to do that.

When you attach a value to $scope it becomes available in your view directly (without needing $scope). For example, $scope.images would be passed in to your directive as just images.

To have the directive process that value as a variable instead of a string it must be defined using an = (as opposed to an @) you can read more about this in the angular directive docs

Here is an example of how this would work:

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>'
  }
})

HTML

  <body ng-app="app">
    <div ng-controller="myCtrl">
      <my-image-gallery images="imageList"></my-image-gallery>
    </div>
  </body>

and here is a plunker of it in action.

Upvotes: 1

Related Questions