Storm Parker
Storm Parker

Reputation: 633

Local image path in AngularJS/JavasScript

I want to create a background image change upon an event (specifically a select option change) and I am having trouble getting the image path on my local environment.

My image path is in directory: http://localhost/webpage1/img/ with the image yellow.jpg

I've put an ng-style directive in my app (<div ng-controller="myCtrl" ng-style="style") and bind it with the controller:

app.controller('myCtrl', function($scope) {
    $scope.options = [
        { type: 'yellow'},
        { type: 'green'}
    ];
    //default image
    $scope.subject = $scope.options[0].type;
    $scope.image = $scope.subject + ".jpg";
    $scope.style = {background: "url(" + $scope.image + ") no-repeat center center fixed"};
    ....
});

However I am stumped with retrieving the file path for my images. I don't want to list out the entire file path since it won't be the same once I put it live, so doing something like $scope.filepath = 'localhost/webpage1/img'; looks very messy and ugly.

Edit: My select options

<select ng-model="subject" name="subject" class="subject" >
    <option ng-repeat="type in options">{{ type.type }}</option>
</select>

Upvotes: 3

Views: 1840

Answers (2)

kolodi
kolodi

Reputation: 1062

Create different classes for backgrounds. Use ng-class on element to trigger style changes based on select option

var app = angular.module('app', []);

app.controller('MainCtrl', function($scope) {
  $scope.options = [
        { type: 'yellow'},
        { type: 'green'}
    ];
});
/* Put your css in here */
.foo {
  width: 100px;
  height: 100px;
  background-repeat: no-repeat;
  background-position: center;
}

.yellow {
  background-image: url(http://www.gettyimages.ca/gi-resources/images/Homepage/Category-Creative/UK/UK_Creative_462809583.jpg);
}

.green {
  background-image: url(http://im.rediff.com/news/2015/dec/24tpoty20.jpg);
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="app">
<div ng-controller="MainCtrl">
  <select ng-model="subject" name="subject" class="subject" >
    <option ng-repeat="type in options">{{ type.type }}</option>
  </select>
  <div class="foo" ng-class="subject"></div>
</div>
</body>

Upvotes: 1

philoniare
philoniare

Reputation: 1653

To address your specific question: There are multiple ways to do it, but you could inject $location and build your url for the image.

Upvotes: 0

Related Questions