title: Best approach to change background image in AngularJs at runtime
body: <p>I want to create generic feature that allows me to change background image of any section.  After going through options provided I found these two approaches. Want to choose best approach to change image because on single page I want multiple times change background facility. It will be available to four to five sections. </p>
  
  <p><strong>Approach</strong></p>
  
  <ol>
  <li><p>Using Directive check this stack overflow <a href="https://stackoverflow.com/questions/13781685/angularjs-ng-src-equivalent-for-background-imageurl">link</a>.</p></li>
  <li><p>Also there is another approach of angular scope variables that we can updates at runtime.</p>
  
  <pre><code>&lt;div ng-style="{'background-image': 'url(/images/' + backgroundImageUrl + ')'}"&gt;&lt;/div&gt;
  </code></pre></li>
  </ol>
  
  <p><strong>Required Usage</strong> ( With respect of Directive )</p>
  
  <pre><code>&lt;body&gt;
      &lt;section backgroundImage url="{{backgroundImageUrl1}}"&gt;
          ...
      &lt;/section&gt;
      &lt;section backgroundImage url="{{backgroundImageUrl2}}"&gt;
          ...
      &lt;/section&gt;
      &lt;section backgroundImage url="{{backgroundImageUrl3}}"&gt;
          ...
      &lt;/section&gt;
      &lt;section backgroundImage url="{{backgroundImageUrl4}}"&gt;
          ...
      &lt;/section&gt;
  &lt;/body&gt;
  </code></pre>
  
  <p>As shown above I am going to update <strong>background-image</strong> attribute for each section. If these property is set inside CSS file, it will reduce time to load images i.e. If we directly add inline css styling in HTML, all images will loaded on DOM load. It will make extra request to server to get images and load them in DOM. I wanted to follow strategy that will reduce loading time in my SPA(Single Page Application).</p>