0

I'm trying to output the name "Sam" on the screen in a ng-show using indexOf, but nothing ever appears. Any help is appreciated.

html

   <head></head>
   <body>
      <div ng-controller="ArrayController">
         <div ng-repeat="product in products">
            <div ng-show="product.name.indexOf('Sam') == 2">
            </div>
         </div>
      </div>


      <script src="bower_components/angular/angular.js"></script>
      <script src="app.js"></script>
   </body>
</html>

angular

var app = angular.module('myApp', []);
app.controller('ArrayController', ['$scope', function($scope){
$scope.products = [
{
name: 'Joe'

},
{
name: 'Bill'
},
{
name: 'Sam'
}
];

}]);
5
  • 2
    Also keep in mind that your test will be never equals to 2. Commented Jul 19, 2016 at 13:46
  • 1
    Sorry but I'd also suggest you learn about what Array.indexOf does developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Jul 19, 2016 at 13:47
  • 2
    @SamiTriki, Even String has indexOf() developer.mozilla.org/en/docs/Web/JavaScript/Reference/… Commented Jul 19, 2016 at 13:48
  • Do you need this https://jsfiddle.net/satpalsingh/hwne9jmu/ Commented Jul 19, 2016 at 13:50
  • Thank you Satpal for showing me a working example. Commented Jul 19, 2016 at 13:52

2 Answers 2

1

Possible solution using ng-if instead of ng-show

<body ng-app="myApp">
      <div ng-controller="ArrayController">
        <div ng-repeat="product in products">
          <div ng-if="product.name.indexOf('Sam') > -1">{{product.name}}
          </div>
        </div>
      </div>
</body>

var app = angular.module('myApp', []);
app.controller('ArrayController', ['$scope', function($scope){
  $scope.products = [
    {
        name: 'Joe'
    },
    {
        name: 'Bill'
    },
    {
        name: 'Sam'
    }
  ];
}]);
Sign up to request clarification or add additional context in comments.

Comments

0
<div ng-show="product.name.indexOf('Sam') == 2"></div>

This will show the div if product.name contains the string "Sam" starting at its third character (i.e. "xxSam"). That probably isn't what you want.

The div is empty, so will not be visible to the user even if the ng-show is truthy. That, too, is probably not what you want.

I'm pretty sure what you do want is this:

<div>{{product.name}}</div>

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.