Loading ng-src images with webpack

Because I also needed thus functionality and found the original answer was far from a perfect solution I ended up figuring it out on my own.

Write a function in the controller:

$scope.loadImage = function(image) {
    return require('/images/' + image);
};

And use it in your ng-src:

<img ng-src="{{loadImage('myImage')}}" />

After that to make dynamic requires work you can use a context.

For example: https://github.com/webpack/webpack/tree/master/examples/require.context#examplejs


If you need an image path that is programmatically generated, it means you have some logic expecting this image to exist. In other words, you should consider this image as a dependency of that piece of logic, thus you need to require it explicitely.

In your JS code (eg: controller)

this.imageUrl = require('path-to-image' + someDynamicValue + '.jpg');

In your template:

<img ng-src="{{::myCtrl.imageUrl}}"/>

Webpack is smart enough to understand the dynamic require statement and bundle your images that will match that expression. Check the documentation for more details: https://webpack.github.io/docs/context.html)