Holly
Holly

Reputation: 7752

AngularJS Remove Substring from String in an expression {{}}

I have this markup in my angularJS mark up

<div class="photo" style="background-image: url('{{item.mageURL}}')"></div>

The {{item.mageURL}} expression producing a string like:

http://example.com/photos/68678/stamp

I would like to change it to:

http://example.com/photos/68678

So far, without success, I've tried...

<div class="photo" style="background-image: url('{{item.mageURL.str.substring( 0, str.indexOf( 'stamp' ) )}}')"></div>

But it just returns an empty string.

Any idea how I can do this in AngularJS

Upvotes: 2

Views: 7666

Answers (3)

georgiy.zhuravlev
georgiy.zhuravlev

Reputation: 475

I think it'll be much better to create a tiny directive for this purpose, like this

app.directive('bgImg', function() {
  return function(scope, elem, attrs) {
    elem.css('background-image', someTransformFn(attrs.bgImg));
  }
})

Long JS-expressions in the templates are the real pain, in comparison with this:

<div bg-img="{{vm.someImg}}">

Upvotes: 0

Mihai Alexandru-Ionut
Mihai Alexandru-Ionut

Reputation: 48357

You have to apply substring method to item.mageURL.str string.

'{{item.mageURL.str.substring( 0, item.mageURL.str.indexOf( '/stamp' ) )}}'

Another method is to use split method.

<div class="photo" style="background-image: url('{{item.mageURL.str.split('/stamp')[0]}}')"></div>

function MyCtrl($scope) {
  $scope.item={
      "mageURL":{
            "str":'http://example.com/photos/68678/stamp'
        }
  };
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app>
  <div ng-controller="MyCtrl">
    <div class="photo" style="background-image: url('{{item.mageURL}}')"></div>
    {{item.mageURL.str.split('/stamp')[0]}}<br>
    {{item.mageURL.str.substring( 0, item.mageURL.str.indexOf( '/stamp' ) )}}
  </div>
</div>

Upvotes: 2

Adrian Bratu
Adrian Bratu

Reputation: 508

please use 'ng-style' https://docs.angularjs.org/api/ng/directive/ngStyle

ng-style="{'background-image' : 'url(' + item.mageURL.str.substring( 0, item.mageURL.str.indexOf( 'stamp' ) )+')'}"

<div class="photo" ng-style="{'background-image' : 'url(' +  item.mageURL.str.substring( 0, item.mageURL.str.indexOf( 'stamp' ) )+')'}"></div>

Upvotes: 1

Related Questions