我有一個數組在輸入框中輸入時被過濾/搜索。當我點擊返回時,輸入文本被追加到數組中。這是偉大的,它的工作原理。indexOf()== -1在推入數組時似乎不起作用
什麼不工作是$ scope.list.indexOf()== -1這是爲了阻止我進入副本。但它不起作用。
我哪裏錯了?
HTML
<!doctype html>
<html ng-app="bgApp">
<head>
<title>List & Tag</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
<!-- Local CSS -->
<link rel="stylesheet" type="text/css" href="./static/css/dev-style.css" />
</head>
<body>
<div ng-controller="listController">
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12 div-title">
<div class="col-xs-6 col-sm-6 col-md-6">
<h1><small>{{title}}</small></h1>
<input type="text" ng-enter="addItem()" ng-model="addName" class="search-query" placeholder="Search">
</div>
</div>
</div>
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12 div-title">
<div class="col-xs-3 col-sm-3 col-md-3">Name of Item</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12 div-row" ng-repeat="item in list | filter:addName">
<div class="col-xs-3 col-sm-3 col-md-3">{{ item.name }}</div>
</div>
</div>
</div>
<!-- AngularJS scripts from CDN -->
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.14/angular-resource.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.14/angular-animate.min.js"></script>
<!-- JQuery scripts from CDN -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<!-- Bootstrap scripts compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
<!-- Locally installed scripts -->
<script src="./js/bgapp.js"></script>
</body>
</html>
的APP,指令&控制器
var bgapp = angular.module('bgApp', [])
.directive('ngEnter', function() {
return function (scope, element, attrs) {
element.bind("keydown keypress", function (event) {
if (event.which === 13) {
scope.$apply(function() {
scope.$eval(attrs.ngEnter, {
'event': event
});
});
event.preventDefault();
}
});
};
});
bgapp.controller('listController', ['$scope', function($scope) {
$scope.title = 'Recent Activity';
$scope.list = [
{name: 'User 1'},
{name: 'Admin 1'},
{name: 'Service 1'},
{name: 'Project 1'},
{name: 'Configuration Item 1'},
{name: 'Task 1'},
{name: 'Incident 1'},
{name: 'Issue 1'},
{name: 'Known Issue 1'},
{name: 'Problem 1'},
{name: 'Knowledge Base 1'},
{name: 'Update 1'},
{name: 'Document 1'},
];
$scope.addItem = function() {
var elem = {name: $scope.addName};
if ($scope.list.indexOf(elem) == -1) {
$scope.list.push(
elem
);
}
};
}]);
在該示例中,「if」語句將檢查數組中是否存在鍵入的內容。如果它不存在,那麼-1是真的,推動會發生。或者我錯過了明顯的東西? – ssedwards
這是一個經典的例子{}!== {}' –