AngularJS アプリケーションは主にコントローラーに依存して、アプリケーション内のデータ フローを制御します。コントローラーは、ng-controller ディレクティブを使用して定義されます。コントローラーは、プロパティ/プロパティと JavaScript オブジェクトを含む関数です。各コントローラーは $scope パラメーターを受け入れて、コントローラーによって制御されるアプリケーション/モジュールを指定します。
1 2 3 | <div ng-app= "" ng-controller= "studentController" >
...
</div>
|
ログイン後にコピー
ここでは、ng-controller ディレクティブを使用してコントローラー StudentController を宣言しています。次のステップとして、studentControllerを次のように定義します
1 2 3 4 5 6 7 8 9 10 11 12 13 | <script>
function studentController( $scope ) {
$scope .student = {
firstName: "yiibai" ,
lastName: "com" ,
fullName: function () {
var studentObject;
studentObject = $scope .student;
return studentObject.firstName + " " + studentObject.lastName;
}
};
}
</script>
|
ログイン後にコピー
- StudentController は $scope を JavaScript オブジェクトのパラメーターとして定義します。
- $scope は、studentController オブジェクトを使用してアプリケーションを表します。
- $scope.student は、studentController オブジェクトのプロパティです。
- FirstName と lastName は、$scope.student オブジェクトの 2 つのプロパティです。デフォルト値を渡しました。
- fullName は $scope.student オブジェクトの関数であり、そのタスクはマージされた名前を返すことです。
- fullName 関数では、student オブジェクトが結合された名前を返すようにします。
- 注として、コントローラー オブジェクトを別の JS ファイルで定義し、関連するファイルを HTML ページに配置することもできます。
これで、ng-model を使用するか、次の式を使用して、studentController 属性を使用できるようになります。
1 2 3 4 | Enter first name: <input type= "text" ng-model= "student.firstName" ><br>
Enter last name: <input type= "text" ng-model= "student.lastName" ><br>
<br>
You are entering: {{student.fullName()}}
|
ログイン後にコピー
- 現在、2 つの入力ボックスがあります:student.firstName とstudent.lastname。
- HTML にstudent.fullName() メソッドが追加されました。
- これで、名と姓の入力ボックスに入力した内容を入力する限り、2 つの名前が自動的に更新されることがわかります。
例
次の例は、コントローラーの使用法を示します。
testAngularJS.html ファイルの内容は次のとおりです:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | <html>
<head>
<title>Angular JS Controller</title>
</head>
<body>
<h2>AngularJS Sample Application</h2>
<div ng-app= "" ng-controller= "studentController" >
Enter first name: <input type= "text" ng-model= "student.firstName" ><br><br>
Enter last name: <input type= "text" ng-model= "student.lastName" ><br>
<br>
You are entering: {{student.fullName()}}
</div>
<script>
function studentController( $scope ) {
$scope .student = {
firstName: "Mahesh" ,
lastName: "Parashar" ,
fullName: function () {
var studentObject;
studentObject = $scope .student;
return studentObject.firstName + " " + studentObject.lastName;
}
};
}
</script>
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js" ></script>
</body>
</html>
|
ログイン後にコピー
出力
Web ブラウザで textAngularJS.html を開くと、次の結果が表示されます:
