javascript - 为什么 Angular 函数需要嵌套?

标签 javascript angularjs

我刚刚开始学习 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/

相关文章:

javascript - 535使用nodemailer的错误身份验证错误

javascript - ng-expression 仅接受最大长度 10 的数字

javascript - 保存文本并将其插入到指定变量之后

javascript - 如何在提交前检查 SQL 数据库的输入值?

angularjs - 创建单元测试,其中每个测试都有其特定的测试数据和测试模拟

javascript - 在 ng-repeat 中将项目添加到数组后保持滚动位置

node.js - 不一致地出现错误 : [$injector:modulerr] Failed to instantiate module

javascript - Angularjs 绑定(bind)到 JSON 将值设置为未定义

javascript - 将 for 循环转换为递归函数

javascript - 无法读取未定义的属性 "toFixed"