1

I am using ng-repeat to print the output in div. Elements in bCrumbs collection start with slash and space and I want to remove them from 1st loop iteration.

My Code:

<div ng-repeat="bCrumb in bCrumbs" id="{{bCrumb.name}}">{{ bCrumb.name }}</div>

the output from {{ bCrumb.name }}:

/ Test1
/ Test2

expected Output:

Test1
/Test2
3
  • Do those bCrumb.name contain slash or not?
    – Rebornix
    Feb 9, 2015 at 12:11
  • yes it contains slash with them but i only want to remove slash from 1st variable.
    – Mayur
    Feb 9, 2015 at 12:13
  • you can check my answer :)
    – Rebornix
    Feb 9, 2015 at 12:17

2 Answers 2

2

You can use ng-repeat-start and ng-repeat-end

<div ng-repeat-start="bCrumb in bCrumbs" ng-if="$first>
    {{ beautify(bCrumb.name) }}
  </div>
  <div ng-repeat-end ng-if="!$first">
    {{ bCrumb.name }}
  </div>

Besides, define a function called beautify in your controller:

$scope.beautify = function (name) {
  return name.replace('/ ', '');
};

You can read the detailed documentation here

update

A better way to handle string beautify is creating a filter to handle it

app.filter('beautify', function () {
    return function (data) {
        return data.replace("/ ", "");
    };
});

Then in your view template:

  <div ng-repeat-start="bCrumb in bCrumbs" ng-if="$first>
    {{ bCrumb.name | beautify }}
  </div>
  <div ng-repeat-end ng-if="!$first">
    {{ bCrumb.name }}
  </div>
2
  • Thanks for answer but it printing: undefinedTest1
    – Mayur
    Feb 9, 2015 at 12:28
  • @Mayur I have updated my answer with two possible solutions for you.
    – Rebornix
    Feb 9, 2015 at 12:46
0

I think you should change your controller (or whatever is producing bCrumbs) to strip the slashes before reaching view. This way it'll be more testable and (hopefully) clear. You could do something like this:

function strip(s) {
    if(s.indexOf('/ ') === 0) {
        return s.substring(2);
    } else {
        return s;
    }
}
$scope.bCrumbs = originalBCrumbs.map(function(bc, idx) {
    return idx === 0 ? strip(bc) : bc;
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.