问题描述
我是angular的新手,并且喜欢A.Freeman的书"Pro Angular JS".因此,我停留在一个示例中,试图了解为什么会触发ng-repeat中的过滤器.这是代码:
I'm new in angular and I reeding A.Freeman's book "Pro Angular JS". So I stuck in one of examples trying to understand why filter in ng-repeat is triggered.Here is the code:
<body ng-controller="sportsStoreCtrl">
<div class="navbar navbar-inverse">
<a class="navbar-brand" href="#">SPORTS STORE</a>
</div>
<div class="panel panel-default row" ng-controller="productListCtrl">
<div class="col-xs-3">
<a ng-click="selectCategory()" class="btn btn-block btn-default btn-lg">Home</a>
<a ng-repeat="item in data.products | orderBy:'category' | unique:'category'" ng-click="selectCategory(item)" class=" btn btn-block btn-default btn-lg">
{{item}}
</a>
</div>
<div class="col-xs-8">
<div class="well" ng-repeat="item in data.products | filter:categoryFilterFn">
<h3>
<strong>{{item.name}}</strong>
<span class="pull-right label label-primary">
{{item.price | currency}}
</span>
</h3>
<span class="lead">{{item.description}}</span>
</div>
</div>
</div>
</body>
和
angular.module("sportsStore")
.controller("productListCtrl", function ($scope, $filter) {
var selectedCategory = null;
$scope.selectCategory = function (newCategory) {
selectedCategory = newCategory;
}
$scope.categoryFilterFn = function (product) {
return selectedCategory == null ||
product.category == selectedCategory;
}
});
categoryFilterFn
是使我感到困惑的一个.为什么当我按下catefory按钮(在ng-click
上使用selectCategory()
方法)时调用它,因为我从未显式调用categoryFilterFn
?
categoryFilterFn
is one that confuses me. Why it's invoking when I press catefory buttons (with selectCategory()
method on ng-click
) since I never call categoryFilterFn
explicitly?
推荐答案
为您解答-由于$ digest.您没有直接调用categoryFilterFn的方法.您的selectedCategory已更改,在categoryFilterFn中使用了该类别,并且categoryFilterFn已绑定到作用域.
Answering you question - because of $digest. You don't have call categoryFilterFn directly. Your selectedCategory has changed which is used in categoryFilterFn and categoryFilterFn is bound to scope.
这篇关于有角度的.为什么过滤器会自动调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!