arrow_backward Back to blog

AngularJS & SVG

If you’re using SVG in your web design you’ve probably read (and hopefully bookmarked) the excellent post Using SVG by Chris Coyier on CSS Tricks. The article is a great introduction to everything you need to know about using SVG on the web.

One of the most powerful aspects of SVG on the web is the ability to style it with CSS. The only downfall to this technique is that the SVG has to be inline. Even if you’re using something to optimize SVG files they can add some serious bloat to your document and can make editing your file cumbersome.

In the Using SVG article he suggests using a back end language like PHP to “clean up the authoring experience.” This is a great suggestion, and I’ve used it, but sometimes I am not using PHP or any backend language. Since I’ve been using Angular lately on a lot of my projects, I have found I can leverage that to import my SVG files. If you’re already using Angular on your project this is super easy, if not, it makes a great way to dip your toe into the Angular waters.

1. Adding AngularJS library to your project.

If you’re already using Angular on your project, skip ahead to step 3. If not, add the Angular library to the head of your HTML document.

<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 

2. Change thetag at the top of your document to the following:

<body ng-app> 

3. Add the following code to import an SVG file:

<ng-include src="'path/to/file/logo.svg'"></ng-include> 

I will frequently inject the SVG into into a div just to give me a little more flexibility when it comes to styling it.

<div class="logo" ng-include="'path/to/file/logo.svg'"></div> 

Got any questions about AngularJS? Weโ€™d love to hear from you.

arrow_backBack

New Project Request