我刚刚开始学习 AngularJS,我看到了一个教程,其中给出了以下示例:
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<ul ng-app="myApp" ng-controller="namesCtrl">
<li ng-repeat="x in names">
{{x | myFormat}}
</li>
</ul>
<script>
var app = angular.module('myApp', []);
app.filter('myFormat', function() {
return function(x) {
var i, c, txt = "";
for (i = 0; i < x.length; i++) {
c = x[i];
if (i % 2 == 0) {
c = c.toUpperCase();
}
txt += c;
}
return txt;
};
});
app.controller('namesCtrl', function($scope) {
$scope.names = [
'Jani',
'Carl',
'Margareth',
'Hege',
'Joe',
'Gustav',
'Birgit',
'Mary',
'Kai'
];
});
</script>
<p>Make your own filters.</p>
<p>This filter, called "myFormat", will uppercase every other character.</p>
</body>
</html>
我想知道 - 为什么函数需要嵌套?为什么我不能写这个:
var app = angular.module('myApp', []);
app.filter('myFormat', function(x) {
var i, c, txt = "";
for (i = 0; i < x.length; i++) {
c = x[i];
if (i % 2 == 0) {
c = c.toUpperCase();
}
txt += c;
}
return txt;
});
还有一个问题 - 在哪里\谁将 x 传递给函数?我知道大多数时候我都会像这样将数据传递给函数 - foo(x,y)
- 这里在哪里?
谢谢!
最佳答案
这是设计使然。 filter
API具有返回function
(过滤逻辑)的函数。基本上可以利用外部来利用 Angular 依赖性。并且内部返回的函数在每个摘要周期上进行评估。
//sample filter
app.filter('upperCase',[ '$window', function($window){ //you could have dependency here
//inner function
return function(x){
return x.toUpperCase();
}
}]);
上面的x
是应用过滤器的值。在你的情况下 {{x | myFormat}}
该参数将是 x
变量范围值。每当您想在过滤器中传递多个参数时,您可以通过在过滤器名称后面提及以 :
{{x | myFormat: y: z}}
关于javascript - 为什么 Angular 函数需要嵌套?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43044293/