user6680 user6680 - 4 months ago 25
AngularJS Question

Angular indexOf not outputting text

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'
}
];

}]);

Answer

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'
    }
  ];
}]);
Comments