22

私はangularjsの初心者で、コントローラーについていくつか質問があります。
これが私のコントローラーの例です:

function exampleController($scope)
{
   $scope.sampleArray = new Array();

   $scope.firstMethod = function()
   {
      //initialize the sampleArray
   };

   $scope.secondMethod = function()
   {
      this.firstMethod();
   };
};

これが私の質問です:

  • どうすれば電話できますfirstMethodsecondMethod?私がそれをした方法は正しいですか、それともより良い方法ですか?
  • コントローラーのコンストラクターを作成するにはどうすればよいですか?sampleArrayを初期化するfirstMethodを呼び出すsecondMethodを呼び出す必要がありますか?
  • HTMLコードから特定のメソッドを呼び出すにはどうすればよいですか?ng-initializeを見つけましたが、使用方法がわかりません。
4

3 に答える 3

32

宣言したのと同じ方法でメソッドを呼び出します。

$scope.secondMethod = function() {
  $scope.firstMethod();
};

次のように HTML から呼び出すこともできます。

<span>{{secondMethod()}}</span>

しかし、コントローラーには実際には「コンストラクター」がありません。通常、コントローラーは関数と同じように使用されます。ただし、コントローラー関数に初期化を配置すると、コンストラクターのように最初に実行されます。

function exampleController($scope) {
  $scope.firstMethod = function() {
    //initialize the sampleArray
  };

  $scope.secondMethod = function() {
    $scope.firstMethod();
  };

  $scope.firstMethod();
}
于 2013-01-18T21:40:44.443 に答える
7

$scope を使用して最初のメソッドを呼び出します。

そう

   $scope.secondMethod = function()
   {
      $scope.firstMethod();
   };

2番目の質問で何を意味するのかよくわかりません。

3 番目の質問については、コントローラーでメソッドを自動的に「オンロード」で実行するか、フロントエンドの角度バインディングを介して実行することができます。

例: 自動的に実行

function exampleController($scope)
{
   $scope.sampleArray = new Array();

   $scope.firstMethod = function()
   {
      //initialize the sampleArray
   };

   $scope.secondMethod = function()
   {
      $scope.firstMethod();
   };


   $scope.secondMethod(); // runs automatically.

};

バインディングで実行

<div ng-controller="ExampleController"> <!-- example controller set up in namespace -->

<button class="btn" ng-click="secondMethod()">Run Second Method</button>

</div>
于 2013-01-18T21:41:21.443 に答える