bumblebee bumblebee - 1 year ago 112
Javascript Question

Replace empty string for a item in ng-repeat

I am just trying to replace empty strings in a item that is part of ng-repeat so I can use this as an id for a div element. Works for the first empty space. I want a global replace and tried something like / /g, but the quotes in the code is messing it up or I am not doing it right.

I tried this

<div ng-repeat="list in list">
<div id="{{list.name.replace(' ','_');}}" ></div>

Answer Source

I recommend you to create a function and call it in your view.

Here's a snippet working:

angular.module('app', [])
  .controller('mainCtrl', function($scope) {
    $scope.list = [
          "name": "noempties"
          "name": "a empty string"
          "name": "more empties a a a a a"
    $scope.replace_chars = function(obj) {
      return obj.name.replace(/\s/g, '_');
<!DOCTYPE html>
<html ng-app="app">

    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script>

  <body ng-controller="mainCtrl">
    <div ng-repeat="lst in list track by $index">
        <!-- The ng-bind was used only to show how it was after replace -->
        <div id="{{replace_chars(lst)}}" ng-bind="'div id: ' + replace_chars(lst)"></div>


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download