2017-03-27 8 views
1

私はAngularJSを学ぶために始めたと私は、次の例を示しますチュートリアル見た:angle関数をネストする必要があるのはなぜですか?

<!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; 
}); 

そしてもう1つの質問 - ここでxは関数に渡されましたか?私は、このようにデータを渡すときのほとんどを知っています - foo(x,y) - ここにはどこですか?

ありがとうございます!

答えて

1

これはデザインによるものです。 filter APIにはfunction(フィルタリングロジック)を返す関数があります。基本的に、外側は角依存性を利用するために利用することができます。また、内部で返された関数は各ダイジェストサイクルで評価されます。

//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}} 
関連する問題