【发布时间】:2016-07-04 04:32:40
【问题描述】:
我正在尝试来自:https://scotch.io/tutorials/building-custom-angularjs-filters#filters-that-actually-filter 的 Angular 自定义过滤器示例,在我的版本中看起来像:
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="demo" >
<div>
<p><strong>Original:</strong></p>
<ul class="list">
<li ng-repeat="x in example1">{{ x.name }}</li>
</ul>
<p><strong>Static Language Filter:</strong></p>
<ul class="list">
<li ng-repeat="x in example1 | staticLanguage">{{x.name }}</li>
</ul>
</div>
</div>
<script>
var app = angular.module('myApp', []);
var counter=0;
app.controller('demo', function($scope){
$scope.example1 = [
{name: 'C#', type : 'static'},
{name: 'PHP', type : 'dynamic'},
{name: 'Go', type : 'static'},
{name: 'JavaScript', type: 'dynamic'},
{name: 'Rust', type: 'static'}
];
});
// Setup the filter
app.filter('staticLanguage', function() { // Create the return function and set the required parameter name to **input**
return function(input) {
counter+=1;
console.log(counter);
var out = [];
// Using the angular.forEach method, go through the array of data and perform the operation of figuring out if the language is statically or dynamically typed.
angular.forEach(input, function(input) {
if (input.type === 'static') {
out.push(input);
}
});
return out;
};
});
</script>
</body>
</html>
从 console.log 看来,由于某种原因,自定义过滤器函数 staticLanguage 被调用了两次,但从代码本身来看,它只被调用了一次:ng-repeat="x in example1 | staticLanguage"
有人知道为什么吗?
P.S 我还没有弄清楚“脏检查”与我的问题有什么关系...... 如果我删除计数器变量并在其中放置一些 console.log("text") 仍然会调用 staticLanguage 函数两次
【问题讨论】:
标签: javascript angularjs