AngularJS问题索引

时间:2015-08-05 04:42:32

标签: angularjs

我正在尝试使用indexOf函数查找提供的元素是否存在于数组中。

但是,我无法根据条件判断是真还是假。

我得到了小提琴。

请说,我需要一些帮助。 http://jsfiddle.net/vMzSq/17/

<div ng-controller="MyCtrl">
 Hello, {{name}}!<br>
 Super? {{contains(name)}}  
 </div>

var myApp = angular.module('myApp',[]);

function MyCtrl($scope) {
    $scope.name = 'Sai';
    $scope.searchNames = ['karthik','Sai']
    $scope.contains = function(searchString) {
        return searchString.indexOf(searchNames) != -1;
}

1 个答案:

答案 0 :(得分:2)

它必须是$scope.searchNames,而不仅仅是searchNames(它未定义)。此外,您需要执行array.indexOf(element),而不是element.indexOf(array)

function MyCtrl($scope) {
  $scope.name = 'Sai';
  $scope.searchNames = ['karthik','Sai']
  $scope.contains = function(searchString) {
      return $scope.searchNames.indexOf(searchString) != -1;
      //  HERE ^^^
  }
}

http://jsfiddle.net/vMzSq/23/

或者,如果您在范围内不需要它,您可以删除它,但要保持一致:

function MyCtrl($scope) {
  $scope.name = 'Sai';
  var searchNames = ['karthik','Sai']
  $scope.contains = function(searchString) {
      return searchNames.indexOf(searchString) != -1;
  }
}

http://jsfiddle.net/vMzSq/22/