0

I'm trying to display the first image in an array that is fed into my directive, however, I do not understand why this doesn't work. Can you please explain?

Script.js file:

angular.module('app',[])

.controller('MyController', function() {
  var self = this;
  self.imageList=[
    'https://upload.wikimedia.org/wikipedia/commons/3/3d/Polar_Bear_AdF.jpg',
    'http://www.polarbearsinternational.org/sites/default/files/styles/media_full/public/00473-10104_0.jpg?itok=uv9Mr5rz',
    'http://www.polarbearsinternational.org/sites/default/files/styles/inside_full/public/sca-000005.jpg?itok=7HybQm2o'
  ];
})

.directive('myImageGallery', function(){
  return {
    restrict: 'E',
    scope:{
      images: '='
    },
    controller: function() {
    },
    controllerAs: 'vm',
    template: '<ul><img images="vm.images" ng-src={{ vm.images[0] }}</li></ul>'
  }
})

HTML:

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

1 Answer 1

3

You just need to correct your template to:

template: '<ul><li><img ng-src="{{images[0]}}"></li></ul>'

You're missing the quotes " " around the ng-src attribute, and you can just access the directive's isolate $scope directly with images[0]. Your img tag is also missing the closing bracket >.

This is how you can access images within the vm controller:

scope:{
  images: '='
},
controller: function($scope) {
  this.images = $scope.images;
},
controllerAs: 'vm',
template: '<ul><li><img ng-src="{{vm.images[0]}}"></li></ul>'

You can use bindToController to automatically bind the directive's isolate scope to the controller. Just make sure you do have the controller property present or it will throw an error.

.directive('myImageGallery', function(){
  return {
    restrict: 'E',
    scope:{
      images: '='
    },
    controller: function() {},
    controllerAs: 'vm',
    bindToController: true,
    template: '<ul><li><img ng-src="{{vm.images[0]}}"</li></ul>'
  };
});
Sign up to request clarification or add additional context in comments.

3 Comments

@nweg Thanks. Updated.
I would use bindToController: true instead of using this.images = $scope.images.
Thanks guys! And yes, bindToController was the missing magic as well. Found a cool article here: toddmotto.com/no-scope-soup-bind-to-controller-angularjs

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.