我正在尝试将过滤器应用于数组,因此当它在JS中发生更改时,它会在HTML中更改(由于双向绑定)。这是我正在使用的控制器:
app.controller('controlador1', ["filterFilter", "$scope", function(filterFilter, $scope) {
this.array = [
{name: 'Tobias'},
{name: 'Jeff'},
{name: 'Brian'},
{name: 'Igor'},
{name: 'James'},
{name: 'Brad'}
];
var active = false;
$scope.applyFilter = function(){
if(!active){
$scope.arrayFiltrado = filterFilter(this.array, "a");
active = true;
}else{
$scope.arrayFiltrado = this.array;
active = false;
}
}
$scope.arrayFiltrado = this.array;
}]);
此外,这是我的HTML模板:
<!DOCTYPE html>
<html ng-app="miApp">
<head>
<meta charset="UTF-8">
<script src="angular.js"></script>
<script src="mainmodule.js"></script>
<link rel="stylesheet" href="bootstrap/css/bootstrap.css">
</head>
<body ng-app="miApp" ng-controller="controlador1">
<button type="button" class="btn btn-default" ng-click="applyFilter()">button</button>
<span ng-repeat="elem in arrayFiltrado">{{elem.name+" "}}</span>
</body>
</html>
我想在单击按钮时应用/停用过滤器,但无论我做什么,如果单击按钮,HTML上都不会显示任何内容。这就像阵列被擦除一样。
谁能告诉我这里缺少什么?
答案 0 :(得分:1)
您只能使用角度绑定来执行此操作。 它可以避免在控制器上编写太多代码并简化逻辑。
JS
app.controller('controlador1', ["filterFilter", "$scope", function(filterFilter, $scope) {
$scope.active = false;
$scope.arrayFiltrado = [
{name: 'Tobias'},
{name: 'Jeff'},
{name: 'Brian'},
{name: 'Igor'},
{name: 'James'},
{name: 'Brad'}
];
$scope.filtering = function(item) {
if(!$scope.active) {
return true;
}
return item.name.indexOf('a') !== -1;
}
}]);
HTML
<body ng-app="miApp" ng-controller="controlador1">
<button type="button" class="btn btn-default" ng-click="active = !active">button</button>
<span ng-repeat="elem in arrayFiltrado | filter:filtering">{{elem.name+" "}}</span>
</body>
答案 1 :(得分:0)
如果您的过滤器工作正常而不是this.array
,则应使用$scope.array
$scope.array = [....];
和
$scope.arrayFiltrado = filterFilter($scope.array, "a");
$scope.arrayFiltrado = $scope.array;