Angularjs-quick-guide

提供:Dev Guides
移動先:案内検索

AngularJS-概要

AngularJSは、オープンソースのWebアプリケーションフレームワークです。 もともと2009年にMisko HeveryとAdam Abronsによって開発されました。 現在はGoogleによって管理されています。 最新バージョンは1.2.21です。

https://docs.angularjs.org/guide/introduction [公式ドキュメント]にあるAngularJSの定義は次のとおりです-

'_AngularJSは、動的Webアプリケーションの構造フレームワークです。 テンプレート言語としてHTMLを使用し、HTMLの構文を拡張して、アプリケーションコンポーネントを明確かつ簡潔に表現できます。 そのデータバインディングと依存性注入により、現在記述しなければならないコードの多くが排除されます。 そして、それはすべてブラウザ内で行われるため、あらゆるサーバー技術との理想的なパートナーになります。_

一般的な機能

AngularJSの一般的な機能は次のとおりです-

  • AngularJSは、リッチインターネットアプリケーション(RIA)を作成できる効率的なフレームワークです。
  • AngularJSは、JavaScriptを使用してクリーンなModel View Controller(MVC)方式でクライアント側アプリケーションを作成するオプションを開発者に提供します。
  • AngularJSで記述されたアプリケーションは、ブラウザーに準拠しています。 AngularJSは、各ブラウザーに適したJavaScriptコードを自動的に処理します。
  • AngularJSはオープンソースであり、完全に無料で、世界中の何千人もの開発者によって使用されています。 Apacheライセンスバージョン2.0でライセンスされています。

全体として、AngularJSは、大規模で高性能で、メンテナンスが容易なWebアプリケーションを構築するためのフレームワークです。

コア機能

AngularJSのコア機能は次のとおりです-

  • データバインディング-モデルとビューコンポーネント間のデータの自動同期です。
  • スコープ-これらはモデルを参照するオブジェクトです。 コントローラとビューの間の接着剤として機能します。
  • Controller -これらは特定のスコープにバインドされたJavaScript関数です。
  • サービス-AngularJSには、XMLHttpRequestを作成するための$ httpなどの組み込みサービスがいくつか付属しています。 これらは、アプリ内で1回だけインスタンス化されるシングルトンオブジェクトです。
  • フィルター-これらは配列からアイテムのサブセットを選択し、新しい配列を返します。
  • ディレクティブ-ディレクティブは、要素、属性、CSSなどのDOM要素のマーカーです。 これらを使用して、新しいカスタムウィジェットとして機能するカスタムHTMLタグを作成できます。 AngularJSには、ngBind、ngModelなどの組み込みディレクティブがあります。
  • テンプレート-これらは、コントローラとモデルからの情報を含むレンダリングされたビューです。 これらは、単一のファイル(indexlなど)または_partials_を使用した1ページの複数のビューです。
  • ルーティング-ビューを切り替える概念です。
  • Model View Whatever -MVWは、アプリケーションをモデル、ビュー、コントローラーと呼ばれる異なる部分に分割するための設計パターンであり、それぞれが異なる責任を持ちます。 AngularJSは、従来の意味でMVCを実装していませんが、MVVM(Model-View-ViewModel)に近いものを実装しています。 Angular JSチームは、ユーモラスにModel View Whateverと呼んでいます。
  • ディープリンク-ディープリンクを使用すると、アプリケーションの状態をURLにエンコードして、ブックマークすることができます。 その後、アプリケーションをURLから同じ状態に復元できます。
  • 依存性注入-AngularJSには、開発者がアプリケーションを簡単に作成、理解、テストできるようにする組み込みの依存性注入サブシステムがあります。

概念

次の図は、AngularJSの重要な部分を示しています。これについては、以降の章で詳しく説明します。

AngularJS Concepts

AngularJSの利点

AngularJSの利点は次のとおりです-

  • 非常にクリーンで保守可能な方法で単一ページアプリケーションを作成する機能を提供します。
  • HTMLへのデータバインディング機能を提供します。 したがって、ユーザーにリッチでレスポンシブなエクスペリエンスを提供します。
  • AngularJSコードはユニットテスト可能です。
  • AngularJSは、依存性注入を使用し、懸念の分離を利用します。
  • AngularJSは再利用可能なコンポーネントを提供します。
  • AngularJSを使用すると、開発者は短いコードでより多くの機能を実現できます。
  • AngularJSでは、ビューは純粋なhtmlページであり、JavaScriptで記述されたコントローラーがビジネス処理を行います。

何よりも、AngularJSアプリケーションは、AndroidおよびiOSベースの携帯電話/タブレットを含む、すべての主要なブラウザーおよびスマートフォンで実行できます。

AngularJSの欠点

AngularJSには多くのメリットがありますが、いくつかの懸念事項があります-

  • 安全でない-JavaScriptのみのフレームワークであるため、AngularJSで記述されたアプリケーションは安全ではありません。 サーバー側の認証と承認は、アプリケーションを安全に保つために必要です。
  • 分解不可-アプリケーションのユーザーがJavaScriptを無効にした場合、基本ページ以外は何も表示されません。

AngularJSディレクティブ

AngularJSフレームワークは3つの主要な部分に分けることができます-

  • ng-app -このディレクティブは、AngularJSアプリケーションを定義してHTMLにリンクします。
  • ng-model -このディレクティブは、AngularJSアプリケーションデータの値をHTML入力コントロールにバインドします。
  • ng-bind -このディレクティブは、AngularJSアプリケーションデータをHTMLタグにバインドします。

AngularJS-環境のセットアップ

この章では、Webアプリケーション開発で使用されるAngularJSライブラリの設定方法について説明します。 また、ディレクトリ構造とその内容についても簡単に説明します。

リンクhttps://angularjs.org/を開くと、AngularJSライブラリをダウンロードするための2つのオプションが表示されます-

AngularJSダウンロード

  • * GitHubで表示*-このボタンをクリックすると、GitHubに転送され、最新のスクリプトがすべて表示されます。
  • * AngularJS 1をダウンロード*-このボタンをクリックすると、画面にダイアログボックスが表示されます-

AngularJSダウンロード

この画面は、次のようにAngular JSを使用するさまざまなオプションを提供します-

  • ローカルでのファイルのダウンロードとホスティング
  • レガシーと最新の2つの異なるオプションがあります。 名前自体は自己記述的です。 Legacyのバージョンは1.2.x未満で、Latestのバージョンは1.3.xです。
  • 最小化、非圧縮、または圧縮されたバージョンを使用することもできます。
  • * CDNアクセス*-CDNにもアクセスできます。 CDNを使用すると、地域のデータセンターにアクセスできます。 この場合、Googleホスト。 CDNは、ファイルをホストする責任を自分のサーバーから一連の外部サーバーに移します。 また、Webページの訪問者が同じCDNからAngularJSのコピーを既にダウンロードしている場合、再ダウンロードする必要がないという利点もあります。

'_このチュートリアルでは、ライブラリのCDNバージョンを使用しています。_

次に、AngularJSライブラリを使用して簡単な例を作成します。 次のようなHTMLファイル_myfirstexamplel_を作成してみましょう-

<!doctype html>
<html>
   <head>
      <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.5.2/angular.min.js"></script>
   </head>

   <body ng-app = "myapp">
      <div ng-controller = "HelloController" >
         <h2>Welcome {{helloTo.title}} to the world of finddevguides!</h2>
      </div>

      <script>
         angular.module("myapp", [])

         .controller("HelloController", function($scope) {
            $scope.helloTo = {};
            $scope.helloTo.title = "AngularJS";
         });
      </script>

   </body>
</html>

上記のコードを詳しく見てみましょう-

AngularJSを含める

AngularJS JavaScriptファイルをHTMLページに含めて、使用できるようにします-

<head>
   <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js">
   </script>
</head>

AngularJSの最新バージョンは、公式Webサイトで確認できます。

AngularJSアプリを指す

次に、HTMLのどの部分にAngularJSアプリが含まれているかを伝える必要があります。 これを行うには、AngularJSアプリのルートHTML要素にng-app属性を追加します。 以下に示すように、html要素またはbody要素に追加できます-

<body ng-app = "myapp">
</body>

View

ビューはこの部分です-

<div ng-controller = "HelloController" >
   <h2>Welcome {{helloTo.title}} to the world of finddevguides!</h2>
</div>

_ng-controller_は、このビューで使用するコントローラーをAngularJSに伝えます。 _helloTo.title_は、HelloTo.titleという名前のモデル値をこの場所のHTMLに書き込むようAngularJSに指示します。

コントローラ

コントローラ部分は-

<script>
   angular.module("myapp", [])

   .controller("HelloController", function($scope) {
      $scope.helloTo = {};
      $scope.helloTo.title = "AngularJS";
   });
</script>

このコードは、_myapp_という名前の角度モジュールにHelloControllerという名前のコントローラー関数を登録します。 link:/angularjs/angularjs_modules [modules]およびlink:/angularjs/angularjs_controllers [controllers]の詳細については、それぞれの章で説明します。 コントローラー関数は、angular.module(…​)。controller(…​)関数呼び出しを介して、angularに登録されます。

$ scopeパラメーターモデルはコントローラー関数に渡されます。 コントローラー関数は_helloTo_ JavaScriptオブジェクトを追加し、そのオブジェクトに_title_フィールドを追加します。

実行

上記のコードを_myfirstexamplel_として保存し、任意のブラウザーで開きます。 あなたは次の出力を見ることができます-

Welcome AngularJS to the world of finddevguides!

ページがブラウザにロードされるとどうなりますか? 見てみましょう−

  • HTMLドキュメントがブラウザにロードされ、ブラウザによって評価されます。
  • AngularJS JavaScriptファイルがロードされ、アンギュラー_global_オブジェクトが作成されます。
  • コントローラ機能を登録するJavaScriptが実行されます。
  • 次に、AngularJSはHTMLをスキャンして、AngularJSアプリとビューを検索します。
  • ビューが見つかると、そのビューを対応するコントローラー機能に接続します。
  • 次に、AngularJSがコントローラー機能を実行します。
  • 次に、コントローラーによって作成されたモデルのデータを使用してビューをレンダリングします。 これでページの準備ができました。

AngularJS-MVCアーキテクチャ

  • [。underline] #M#* odel * [。underline] #V#* iew * [。underline] #C#**一般的に呼ばれているトローラーまたはMVCは、開発のためのソフトウェア設計パターンですWebアプリケーション。 モデルビューコントローラーパターンは、次の3つの部分で構成されています-
    • モデル-データの維持を担当するパターンの最低レベルです。
    • 表示-データのすべてまたは一部をユーザーに表示します。
    • コントローラー-モデルとビューの間の相互作用を制御するソフトウェアコードです。

MVCは、アプリケーションロジックをユーザーインターフェイスレイヤーから分離し、懸念の分離をサポートするため、人気があります。 コントローラーはアプリケーションに対するすべてのリクエストを受信し、モデルと連携してビューに必要なデータを準備します。 ビューは、コントローラーによって準備されたデータを使用して、最終的な表示可能な応答を生成します。 MVC抽象化は、次のようにグラフィカルに表現できます。

AngularJS MVC

モデル

モデルは、アプリケーションデータの管理を担当します。 ビューからの要求とコントローラーからの指示に応答して、それ自体を更新します。

景色

データを提示するというコントローラーの決定によってトリガーされる、特定の形式でのデータの提示。 これらは、JSP、ASP、PHPなどのスクリプトベースのテンプレートシステムであり、AJAXテクノロジーとの統合が非常に簡単です。

コントローラー

コントローラーはユーザー入力に応答し、データモデルオブジェクトで相互作用を実行します。 コントローラーは入力を受け取り、それを検証してから、データモデルの状態を変更するビジネスオペレーションを実行します。

AngularJSは、MVCベースのフレームワークです。 今後の章では、AngularJSがMVC方法論をどのように使用するかを説明します。

AngularJS-最初のアプリケーション

AngularJSを使用して実際の_Hello World!_アプリケーションを作成する前に、AngularJSアプリケーションの一部を見てみましょう。 AngularJSアプリケーションは、次の3つの重要な部分で構成されています-

  • ng-app -このディレクティブは、AngularJSアプリケーションを定義してHTMLにリンクします。
  • ng-model -このディレクティブは、AngularJSアプリケーションデータの値をHTML入力コントロールにバインドします。
  • ng-bind -このディレクティブは、AngularJSアプリケーションデータをHTMLタグにバインドします。

AngularJSアプリケーションの作成

ステップ1:フレームワークをロードする

純粋なJavaScriptフレームワークであるため、<Script>タグを使用して追加できます。

<script
   src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
</script>

ステップ2:ng-appディレクティブを使用してAngularJSアプリケーションを定義する

<div ng-app = "">
   ...
</div>

ステップ3:ng-modelディレクティブを使用してモデル名を定義する

<p>Enter your Name: <input type = "text" ng-model = "name"></p>

ステップ4:ng-bindディレクティブを使用して定義された上記のモデルの値をバインドする

<p>Hello <span ng-bind = "name"></span>!</p>

AngularJSアプリケーションの実行

HTMLページで上記の3つの手順を使用します。

testAngularJS

<html>
   <head>
      <title>AngularJS First Application</title>
   </head>

   <body>
      <h1>Sample Application</h1>

      <div ng-app = "">
         <p>Enter your Name: <input type = "text" ng-model = "name"></p>
         <p>Hello <span ng-bind = "name"></span>!</p>
      </div>

      <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
      </script>

   </body>
</html>

出力

ファイル_testAngularJS_をWebブラウザーで開きます。 名前を入力して結果を確認します。

AngularJSとHTMLの統合方法

  • ng-appディレクティブは、AngularJSアプリケーションの開始を示します。
  • ng-modelディレクティブはnameという名前のモデル変数を作成します。これはHTMLページで使用でき、ng-appディレクティブを持つdiv内で使用できます。
  • ng-bindは、ユーザーがテキストボックスに入力を入力するたびに、HTML <span>タグに表示される名前モデルを使用します。
  • Closing </div>タグは、AngularJSアプリケーションの終了を示します。

AngularJS-ディレクティブ

AngularJSディレクティブは、HTMLを拡張するために使用されます。 これらは、 ng -prefixで始まる特別な属性です。 私たちは次のディレクティブを議論しましょう-

  • ng-app -このディレクティブはAngularJSアプリケーションを起動します。
  • ng-init -このディレクティブは、アプリケーションデータを初期化します。
  • ng-model -このディレクティブは、AngularJSで使用される変数であるモデルを定義します。
  • ng-repeat -このディレクティブは、コレクション内のアイテムごとにHTML要素を繰り返します。

ng-appディレクティブ

ng-appディレクティブは、AngularJSアプリケーションを起動します。 ルート要素を定義します。 AngularJS Applicationを含むWebページがロードされると、アプリケーションを自動的に初期化またはブートストラップします。 また、AngularJSアプリケーションでさまざまなAngularJSモジュールをロードするためにも使用されます。 次の例では、<div>要素のng-app属性を使用してデフォルトのAngularJSアプリケーションを定義します。

<div ng-app = "">
   ...
</div>

ng-initディレクティブ

ng-initディレクティブは、AngularJSアプリケーションデータを初期化します。 変数に値を割り当てるために使用されます。 次の例では、国の配列を初期化します。 国の配列を定義するためにJSON構文を使用します。

<div ng-app = "" ng-init = "countries = [{locale:'en-US',name:'United States'},
   {locale:'en-GB',name:'United Kingdom'}, {locale:'en-FR',name:'France'}]">
   ...
</div>

ng-modelディレクティブ

ng-modelディレクティブは、AngularJSアプリケーションで使用されるモデル/変数を定義します。 次の例では、_name_という名前のモデルを定義します。

<div ng-app = "">
   ...
   <p>Enter your Name: <input type = "text" ng-model = "name"></p>
</div>

ng-repeatディレクティブ

ng-repeatディレクティブは、コレクション内の各アイテムに対してHTML要素を繰り返します。 次の例では、国の配列を反復処理します。

<div ng-app = "">
   ...
   <p>List of Countries with locale:</p>

   <ol>
      <li ng-repeat = "country in countries">
         {{ 'Country: ' + country.name + ', Locale: ' + country.locale }}
      </li>
   </ol>
</div>

次の例は、上記のすべてのディレクティブの使用方法を示しています。

testAngularJS

<html>
   <head>
      <title>AngularJS Directives</title>
   </head>

   <body>
      <h1>Sample Application</h1>

      <div ng-app = "" ng-init = "countries = [{locale:'en-US',name:'United States'},
         {locale:'en-GB',name:'United Kingdom'}, {locale:'en-FR',name:'France'}]">
         <p>Enter your Name: <input type = "text" ng-model = "name"></p>
         <p>Hello <span ng-bind = "name"></span>!</p>
         <p>List of Countries with locale:</p>

         <ol>
            <li ng-repeat = "country in countries">
               {{ 'Country: ' + country.name + ', Locale: ' + country.locale }}
            </li>
         </ol>
      </div>

      <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
      </script>

   </body>
</html>

出力

ファイル_testAngularJS_をWebブラウザーで開きます。 名前を入力して結果を確認します。

AngularJS-式

式は、アプリケーションデータをHTMLにバインドするために使用されます。 式は、\ {\ {expression}}のように二重中括弧内に記述されます。 式は、ngbindディレクティブと同様に動作します。 AngularJS式は純粋なJavaScript式であり、使用されているデータを出力します。

数字を使う

<p>Expense on Books : {{cost *quantity}} Rs</p>

文字列を使用する

<p>Hello {{student.firstname + " " + student.lastname}}!</p>

オブジェクトを使用する

<p>Roll No: {{student.rollno}}</p>

配列を使用する

<p>Marks(Math): {{marks[3]}}</p>

次の例は、上記のすべての式の使用を示しています-

testAngularJS

<html>
   <head>
      <title>AngularJS Expressions</title>
   </head>

   <body>
      <h1>Sample Application</h1>

      <div ng-app = "" ng-init = "quantity = 1;cost = 30;
         student = {firstname:'Mahesh',lastname:'Parashar',rollno:101};
         marks = [80,90,75,73,60]">
         <p>Hello {{student.firstname + " " + student.lastname}}!</p>
         <p>Expense on Books : {{cost* quantity}} Rs</p>
         <p>Roll No: {{student.rollno}}</p>
         <p>Marks(Math): {{marks[3]}}</p>
      </div>

      <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
      </script>

   </body>
</html>

出力

ファイル_testAngularJS_をWebブラウザーで開き、結果を確認します。

AngularJS-コントローラー

AngularJSアプリケーションは、主にコントローラーを使用して、アプリケーション内のデータの流れを制御します。 コントローラーは、_ng-controller_ディレクティブを使用して定義されます。 コントローラーは、属性/プロパティ、および関数を含むJavaScriptオブジェクトです。 各コントローラーは、パラメーターとして$ scopeを受け入れます。これは、コントローラーが処理する必要があるアプリケーション/モジュールを参照します。

<div ng-app = "" ng-controller = "studentController">
   ...
</div>

ここでは、ng-controllerディレクティブを使用して、_studentController_という名前のコントローラーを宣言します。 次のように定義します-

<script>
   function studentController($scope) {
      $scope.student = {
         firstName: "Mahesh",
         lastName: "Parashar",

         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のstudentプロパティを使用できます-

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()}}
  • student.firstNameとstudent.lastnameを2つの入力ボックスにバインドしました。
  • student.fullName()をHTMLにバインドしました。
  • これで、姓と名の入力ボックスに何かを入力するたびに、フルネームが自動的に更新されるのを見ることができます。

次の例は、コントローラの使用を示しています-

testAngularJS

<html>
   <head>
      <title>Angular JS Controller</title>
      <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
      </script>
   </head>

   <body>
      <h2>AngularJS Sample Application</h2>

      <div ng-app = "mainApp" 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>
         var mainApp = angular.module("mainApp", []);

         mainApp.controller('studentController', function($scope) {
            $scope.student = {
               firstName: "Mahesh",
               lastName: "Parashar",

               fullName: function() {
                  var studentObject;
                  studentObject = $scope.student;
                  return studentObject.firstName + " " + studentObject.lastName;
               }
            };
         });
      </script>

   </body>
</html>

出力

ファイル_testAngularJS_をWebブラウザーで開き、結果を確認します。

AngularJS-フィルター

フィルタは、データを変更するために使用されます。 それらは、パイプ(|)文字を使用して、表現またはディレクティブでクラブ化できます。 次のリストは、一般的に使用されるフィルターを示しています。

Sr.No. Name & Description
1

uppercase

テキストを大文字のテキストに変換します。

2

lowercase

テキストを小文字のテキストに変換します。

3

currency

通貨形式でテキストをフォーマットします。

4

filter

指定された基準に基づいて、配列をそのサブセットにフィルターします。

5

orderby

指定された基準に基づいて配列を順序付けます。

大文字フィルター

パイプ文字を使用して、大文字のフィルターを式に追加します。 ここでは、大文字のフィルターを追加して、生徒名をすべて大文字で印刷します。

Enter first name:<input type = "text" ng-model = "student.firstName">
Enter last name: <input type = "text" ng-model = "student.lastName">
Name in Upper Case: {{student.fullName() | uppercase}}

小文字フィルター

パイプ文字を使用して、小文字のフィルターを式に追加します。 ここでは、小文字のフィルタを追加して、学生名をすべて小文字で印刷します。

Enter first name:<input type = "text" ng-model = "student.firstName">
Enter last name: <input type = "text" ng-model = "student.lastName">
Name in Lower Case: {{student.fullName() | lowercase}}

通貨フィルター

パイプ文字を使用して数値を返す式に通貨フィルターを追加します。 ここでは、通貨形式を使用して印刷料金に通貨フィルターを追加しました。

Enter fees: <input type = "text" ng-model = "student.fees">
fees: {{student.fees | currency}}

フィルタ

必要なサブジェクトのみを表示するには、フィルターとしてsubjectNameを使用します。

Enter subject: <input type = "text" ng-model = "subjectName">
Subject:
<ul>
   <li ng-repeat = "subject in student.subjects | filter: subjectName">
      {{ subject.name + ', marks:' + subject.marks }}
   </li>
</ul>

OrderByフィルター

件名をマークで並べるには、orderByマークを使用します。

Subject:
<ul>
   <li ng-repeat = "subject in student.subjects | orderBy:'marks'">
      {{ subject.name + ', marks:' + subject.marks }}
   </li>
</ul>

次の例は、上記のすべてのフィルターの使用を示しています。

testAngularJS

<html>
   <head>
      <title>Angular JS Filters</title>
      <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
      </script>
   </head>

   <body>
      <h2>AngularJS Sample Application</h2>

      <div ng-app = "mainApp" ng-controller = "studentController">
         <table border = "0">
            <tr>
               <td>Enter first name:</td>
               <td><input type = "text" ng-model = "student.firstName"></td>
            </tr>
            <tr>
               <td>Enter last name: </td>
               <td><input type = "text" ng-model = "student.lastName"></td>
            </tr>
            <tr>
               <td>Enter fees: </td>
               <td><input type = "text" ng-model = "student.fees"></td>
            </tr>
            <tr>
               <td>Enter subject: </td>
               <td><input type = "text" ng-model = "subjectName"></td>
            </tr>
         </table>
         <br/>

         <table border = "0">
            <tr>
               <td>Name in Upper Case: </td><td>{{student.fullName() | uppercase}}</td>
            </tr>
            <tr>
               <td>Name in Lower Case: </td><td>{{student.fullName() | lowercase}}</td>
            </tr>
            <tr>
               <td>fees: </td><td>{{student.fees | currency}}
               </td>
            </tr>
            <tr>
               <td>Subject:</td>
               <td>
                  <ul>
                     <li ng-repeat = "subject in student.subjects | filter: subjectName |orderBy:'marks'">
                        {{ subject.name + ', marks:' + subject.marks }}
                     </li>
                  </ul>
               </td>
            </tr>
         </table>
      </div>

      <script>
         var mainApp = angular.module("mainApp", []);

         mainApp.controller('studentController', function($scope) {
            $scope.student = {
               firstName: "Mahesh",
               lastName: "Parashar",
               fees:500,

               subjects:[
                  {name:'Physics',marks:70},
                  {name:'Chemistry',marks:80},
                  {name:'Math',marks:65}
               ],
               fullName: function() {
                  var studentObject;
                  studentObject = $scope.student;
                  return studentObject.firstName + " " + studentObject.lastName;
               }
            };
         });
      </script>

   </body>
</html>

出力

ファイル_testAngularJS_をWebブラウザーで開きます。 結果をご覧ください。

AngularJS-テーブル

通常、テーブルデータは繰り返し可能です。 ng-repeatディレクティブを使用すると、テーブルを簡単に描画できます。 次の例は、ng-repeatディレクティブを使用してテーブルを描画する方法を示しています-

<table>
   <tr>
      <th>Name</th>
      <th>Marks</th>
   </tr>

   <tr ng-repeat = "subject in student.subjects">
      <td>{{ subject.name }}</td>
      <td>{{ subject.marks }}</td>
   </tr>
</table>

CSSスタイルを使用して、テーブルのスタイルを設定できます。

<style>
   table, th , td {
      border: 1px solid grey;
      border-collapse: collapse;
      padding: 5px;
   }
   table tr:nth-child(odd) {
      background-color: #f2f2f2;
   }
   table tr:nth-child(even) {
      background-color: #ffffff;
   }
</style>

次の例は、上記のすべてのディレクティブの使用方法を示しています。

testAngularJS

<html>
   <head>
      <title>Angular JS Table</title>
      <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>

      <style>
         table, th , td {
            border: 1px solid grey;
            border-collapse: collapse;
            padding: 5px;
         }
         table tr:nth-child(odd) {
            background-color: #f2f2f2;
         }
         table tr:nth-child(even) {
            background-color: #ffffff;
         }
      </style>
   </head>

   <body>
      <h2>AngularJS Sample Application</h2>
      <div ng-app = "mainApp" ng-controller = "studentController">

         <table border = "0">
            <tr>
               <td>Enter first name:</td>
               <td><input type = "text" ng-model = "student.firstName"></td>
            </tr>
            <tr>
               <td>Enter last name: </td>
               <td>
                  <input type = "text" ng-model = "student.lastName">
               </td>
            </tr>
            <tr>
               <td>Name: </td>
               <td>{{student.fullName()}}</td>
            </tr>
            <tr>
               <td>Subject:</td>

               <td>
                  <table>
                     <tr>
                        <th>Name</th>.
                        <th>Marks</th>
                     </tr>
                     <tr ng-repeat = "subject in student.subjects">
                        <td>{{ subject.name }}</td>
                        <td>{{ subject.marks }}</td>
                     </tr>
                  </table>
               </td>
            </tr>
         </table>
      </div>

      <script>
         var mainApp = angular.module("mainApp", []);

         mainApp.controller('studentController', function($scope) {
            $scope.student = {
               firstName: "Mahesh",
               lastName: "Parashar",
               fees:500,

               subjects:[
                  {name:'Physics',marks:70},
                  {name:'Chemistry',marks:80},
                  {name:'Math',marks:65},
                  {name:'English',marks:75},
                  {name:'Hindi',marks:67}
               ],
               fullName: function() {
                  var studentObject;
                  studentObject = $scope.student;
                  return studentObject.firstName + " " + studentObject.lastName;
               }
            };
         });
      </script>

   </body>
</html>

出力

ファイル_testAngularJS_をWebブラウザーで開き、結果を確認します。

AngularJS-HTML DOM

次のディレクティブは、アプリケーションデータをHTML DOM要素の属性にバインドするために使用されます-

Sr.No. Name & Description
1

ng-disabled

特定のコントロールを無効にします。

2

ng-show

指定されたコントロールを表示します。

3

ng-hide

特定のコントロールを非表示にします。

4

ng-click

AngularJSクリックイベントを表します。

ng-disabledディレクティブ

ng-disabled属性をHTMLボタンに追加し、モデルに渡します。 モデルをチェックボックスにバインドし、バリエーションを確認します。

<input type = "checkbox" ng-model = "enableDisableButton">Disable Button
<button ng-disabled = "enableDisableButton">Click Me!</button>

ng-showディレクティブ

ng-show属性をHTMLボタンに追加し、モデルに渡します。 モデルをチェックボックスにバインドし、バリエーションを確認します。

<input type = "checkbox" ng-model = "showHide1">Show Button
<button ng-show = "showHide1">Click Me!</button>

ng-hideディレクティブ

ng-hide属性をHTMLボタンに追加し、モデルに渡します。 モデルをチェックボックスにバインドし、バリエーションを確認します。

<input type = "checkbox" ng-model = "showHide2">Hide Button
<button ng-hide = "showHide2">Click Me!</button>

ng-clickディレクティブ

ng-click属性をHTMLボタンに追加し、モデルを更新します。 モデルをHTMLにバインドし、バリエーションを確認します。

<p>Total click: {{ clickCounter }}</p>
<button ng-click = "clickCounter = clickCounter + 1">Click Me!</button>

次の例は、上記のすべてのディレクティブの使用を示しています。

testAngularJS

<html>
   <head>
      <title>AngularJS HTML DOM</title>
   </head>

   <body>
      <h2>AngularJS Sample Application</h2>

      <div ng-app = "">
         <table border = "0">
            <tr>
               <td><input type = "checkbox" ng-model = "enableDisableButton">Disable Button</td>
               <td><button ng-disabled = "enableDisableButton">Click Me!</button></td>
            </tr>
            <tr>
               <td><input type = "checkbox" ng-model = "showHide1">Show Button</td>
               <td><button ng-show = "showHide1">Click Me!</button></td>
            </tr>
            <tr>
               <td><input type = "checkbox" ng-model = "showHide2">Hide Button</td>
               <td><button ng-hide = "showHide2">Click Me!</button></td>
            </tr>
            <tr>
               <td><p>Total click: {{ clickCounter }}</p></td>
               <td><button ng-click = "clickCounter = clickCounter + 1">Click Me!</button></td>
            </tr>
         </table>
      </div>

      <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
      </script>

   </body>
</html>

出力

ファイル_testAngularJS_をWebブラウザーで開き、結果を確認します。

AngularJS-モジュール

AngularJSはモジュラーアプローチをサポートしています。 モジュールは、サービス、コントローラー、アプリケーションなどのロジックを分離するために使用されます。 コードから、コードをクリーンに維持します。 モジュールを個別のjsファイルで定義し、module.jsファイルに従って名前を付けます。 次の例では、2つのモジュールを作成します-

  • アプリケーションモジュール-コントローラでアプリケーションを初期化するために使用されます。
  • Controller Module -コントローラーの定義に使用されます。

アプリケーションモジュール

これは、次のコードを含む_mainApp.js_という名前のファイルです-

var mainApp = angular.module("mainApp", []);

ここでは、angle.module関数を使用してアプリケーション mainApp モジュールを宣言し、空の配列を渡します。 通常、この配列には依存モジュールが含まれます。

コントローラーモジュール

studentController.js

mainApp.controller("studentController", function($scope) {
   $scope.student = {
      firstName: "Mahesh",
      lastName: "Parashar",
      fees:500,

      subjects:[
         {name:'Physics',marks:70},
         {name:'Chemistry',marks:80},
         {name:'Math',marks:65},
         {name:'English',marks:75},
         {name:'Hindi',marks:67}
      ],
      fullName: function() {
         var studentObject;
         studentObject = $scope.student;
         return studentObject.firstName + " " + studentObject.lastName;
      }
   };
});

ここでは、mainApp.controller関数を使用してコントローラー studentController モジュールを宣言します。

モジュールを使用する

<div ng-app = "mainApp" ng-controller = "studentController">
   ...
   <script src = "mainApp.js"></script>
   <script src = "studentController.js"></script>

</div>

ここでは、ng-appディレクティブを使用してアプリケーションモジュールを使用し、ngcontrollerディレクティブを使用してコントローラーを使用します。 メインのHTMLページにmainApp.jsとstudentController.jsをインポートします。

次の例は、上記のすべてのモジュールの使用を示しています。

testAngularJS

<html>
   <head>
      <title>Angular JS Modules</title>
      <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
      <script src = "/angularjs/src/module/mainApp.js"></script>
      <script src = "/angularjs/src/module/studentController.js"></script>

      <style>
         table, th , td {
            border: 1px solid grey;
            border-collapse: collapse;
            padding: 5px;
         }
         table tr:nth-child(odd) {
            background-color: #f2f2f2;
         }
         table tr:nth-child(even) {
            background-color: #ffffff;
         }
      </style>
   </head>

   <body>
      <h2>AngularJS Sample Application</h2>
      <div ng-app = "mainApp" ng-controller = "studentController">

         <table border = "0">
            <tr>
               <td>Enter first name:</td>
               <td><input type = "text" ng-model = "student.firstName"></td>
            </tr>
            <tr>
               <td>Enter last name: </td>
               <td><input type = "text" ng-model = "student.lastName"></td>
            </tr>
            <tr>
               <td>Name: </td>
               <td>{{student.fullName()}}</td>
            </tr>
            <tr>
               <td>Subject:</td>

               <td>
                  <table>
                     <tr>
                        <th>Name</th>
                        <th>Marks</th>
                     </tr>
                     <tr ng-repeat = "subject in student.subjects">
                        <td>{{ subject.name }}</td>
                        <td>{{ subject.marks }}</td>
                     </tr>
                  </table>
               </td>
            </tr>
         </table>
      </div>

   </body>
</html>

mainApp.js

var mainApp = angular.module("mainApp", []);

studentController.js

mainApp.controller("studentController", function($scope) {
   $scope.student = {
      firstName: "Mahesh",
      lastName: "Parashar",
      fees:500,

      subjects:[
         {name:'Physics',marks:70},
         {name:'Chemistry',marks:80},
         {name:'Math',marks:65},
         {name:'English',marks:75},
         {name:'Hindi',marks:67}
      ],
      fullName: function() {
         var studentObject;
         studentObject = $scope.student;
         return studentObject.firstName + " " + studentObject.lastName;
      }
   };
});

出力

ファイル_textAngularJS_をWebブラウザーで開きます。 結果をご覧ください。

AngularJS-フォーム

AngularJSは、フォームの入力と検証を強化します。 ng-clickイベントを使用してクリックボタンを処理し、$ dirtyおよび$ invalidフラグを使用してシームレスな方法で検証を実行できます。 novalidateをフォーム宣言とともに使用して、ブラウザー固有の検証を無効にします。 フォームコントロールは、AngularJSイベントを多用します。 最初にイベントを見てみましょう。

イベント

AngularJSは、HTMLコントロールに関連付けられた複数のイベントを提供します。 たとえば、ng-clickディレクティブは通常、ボタンに関連付けられています。 AngularJSは以下のイベントをサポートしています-

  • ng-click
  • ng-dbl-クリック
  • ng-mousedown
  • ng-mouseup
  • ng-mouseenter
  • ng-mouseleave
  • ng-mousemove
  • ng-mouseover
  • ng-keydown
  • ng-keyup
  • ng-keypress
  • ng-change

ng-click

ボタンのクリック時ディレクティブを使用して、フォームのデータをリセットします。

<input name = "firstname" type = "text" ng-model = "firstName" required>
<input name = "lastname" type = "text" ng-model = "lastName" required>
<input name = "email" type = "email" ng-model = "email" required>
<button ng-click = "reset()">Reset</button>

<script>
   function studentController($scope) {
      $scope.reset = function() {
         $scope.firstName = "Mahesh";
         $scope.lastName = "Parashar";
         $scope.email = "[email protected]";
      }

      $scope.reset();
   }
</script>

データを検証する

以下を使用してエラーを追跡できます。

  • $ dirty -値が変更されたことを示します。
  • $ invalid -入力された値が無効であることを示します。
  • $ error -正確なエラーを示します。

次の例は、上記のすべてのディレクティブを示しています。

testAngularJS

<html>
   <head>
      <title>Angular JS Forms</title>
      <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>

      <style>
         table, th , td {
            border: 1px solid grey;
            border-collapse: collapse;
            padding: 5px;
         }
         table tr:nth-child(odd) {
            background-color: #f2f2f2;
         }
         table tr:nth-child(even) {
            background-color: #ffffff;
         }
      </style>

   </head>
   <body>

      <h2>AngularJS Sample Application</h2>
      <div ng-app = "mainApp" ng-controller = "studentController">

         <form name = "studentForm" novalidate>
            <table border = "0">
               <tr>
                  <td>Enter first name:</td>
                  <td><input name = "firstname" type = "text" ng-model = "firstName" required>
                     <span style = "color:red" ng-show = "studentForm.firstname.$dirty && studentForm.firstname.$invalid">
                        <span ng-show = "studentForm.firstname.$error.required">First Name is required.</span>
                     </span>
                  </td>
               </tr>

               <tr>
                  <td>Enter last name: </td>
                  <td><input name = "lastname"  type = "text" ng-model = "lastName" required>
                     <span style = "color:red" ng-show = "studentForm.lastname.$dirty && studentForm.lastname.$invalid">
                        <span ng-show = "studentForm.lastname.$error.required">Last Name is required.</span>
                     </span>
                  </td>
               </tr>

               <tr>
                  <td>Email: </td><td><input name = "email" type = "email" ng-model = "email" length = "100" required>
                     <span style = "color:red" ng-show = "studentForm.email.$dirty && studentForm.email.$invalid">
                        <span ng-show = "studentForm.email.$error.required">Email is required.</span>
                        <span ng-show = "studentForm.email.$error.email">Invalid email address.</span>
                     </span>
                  </td>
               </tr>

               <tr>
                  <td>
                     <button ng-click = "reset()">Reset</button>
                  </td>
                  <td>
                     <button ng-disabled = "studentForm.firstname.$dirty &&
                        studentForm.firstname.$invalid || studentForm.lastname.$dirty &&
                        studentForm.lastname.$invalid || studentForm.email.$dirty &&
                        studentForm.email.$invalid" ng-click="submit()">Submit</button>
                  </td>
               </tr>

            </table>
         </form>
      </div>

      <script>
         var mainApp = angular.module("mainApp", []);

         mainApp.controller('studentController', function($scope) {
            $scope.reset = function() {
               $scope.firstName = "Mahesh";
               $scope.lastName = "Parashar";
               $scope.email = "[email protected]";
            }

            $scope.reset();
         });
      </script>

   </body>
</html>

出力

ファイル_testAngularJS_をWebブラウザーで開き、結果を確認します。

AngularJS-含まれています

HTMLページ内にHTMLページを埋め込むことは、HTMLではサポートされていません。 この機能を実現するには、次のオプションのいずれかを使用できます-

  • * Ajaxの使用*-対応するHTMLページを取得するためにサーバー呼び出しを行い、HTMLコントロールのinnerHTMLで設定します。
  • サーバー側インクルードの使用-JSP、PHP、およびその他のWebサイドサーバーテクノロジーには、動的ページ内にHTMLページを含めることができます。

AngularJSを使用すると、ng-includeディレクティブを使用してHTMLページ内にHTMLページを埋め込むことができます。

<div ng-app = "" ng-controller = "studentController">
   <div ng-include = "'main'"></div>
   <div ng-include = "'subjects'"></div>
</div>

tryAngularJS

<html>
   <head>
      <title>Angular JS Includes</title>
      <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
      </script>

      <style>
         table, th , td {
            border: 1px solid grey;
            border-collapse: collapse;
            padding: 5px;
         }
         table tr:nth-child(odd) {
            background-color: #f2f2f2;
         }
         table tr:nth-child(even) {
            background-color: #ffffff;
         }
      </style>
   </head>

   <body>
      <h2>AngularJS Sample Application</h2>

      <div ng-app = "mainApp" ng-controller = "studentController">
         <div ng-include = "'/angularjs/src/include/main'"></div>
         <div ng-include = "'/angularjs/src/include/subjects'"></div>
      </div>

      <script>
         var mainApp = angular.module("mainApp", []);

         mainApp.controller('studentController', function($scope) {
            $scope.student = {
               firstName: "Mahesh",
               lastName: "Parashar",
               fees:500,

               subjects:[
                  {name:'Physics',marks:70},
                  {name:'Chemistry',marks:80},
                  {name:'Math',marks:65},
                  {name:'English',marks:75},
                  {name:'Hindi',marks:67}
               ],
               fullName: function() {
                  var studentObject;
                  studentObject = $scope.student;
                  return studentObject.firstName + " " + studentObject.lastName;
               }
            };
         });
      </script>

   </body>
</html>

main

<table border = "0">
   <tr>
      <td>Enter first name:</td>
      <td><input type = "text" ng-model = "student.firstName"></td>
   </tr>

   <tr>
      <td>Enter last name: </td>
      <td><input type = "text" ng-model = "student.lastName"></td>
   </tr>

   <tr>
      <td>Name: </td>
      <td>{{student.fullName()}}</td>
   </tr>
</table>

科目

<p>Subjects:</p>
<table>
   <tr>
      <th>Name</th>
      <th>Marks</th>
   </tr>

   <tr ng-repeat = "subject in student.subjects">
      <td>{{ subject.name }}</td>
      <td>{{ subject.marks }}</td>
   </tr>
</table>

出力

この例を実行するには、testAngularJS、main、、および_subjects_をWebサーバーにデプロイする必要があります。 WebブラウザーでサーバーのURLを使用して_testAngularJS_ファイルを開き、結果を確認します。

AngularJS-Ajax

AngularJSは、サーバーからデータを読み取るサービスとして機能する$ httpコントロールを提供します。 サーバーは、目的のレコードを取得するためにデータベース呼び出しを行います。 AngularJSにはJSON形式のデータが必要です。 データの準備ができたら、次の方法で$ httpを使用してサーバーからデータを取得できます-

function studentController($scope,$https:) {
   var url = "data.txt";

   $https:.get(url).success( function(response) {
      $scope.students = response;
   });
}

ここで、ファイルdata.txtには学生レコードが含まれています。 $ httpサービスはajax呼び出しを行い、プロパティの学生に応答を設定します。 学生モデルを使用して、HTMLで表を描画できます。

data.txt

[
   {
      "Name" : "Mahesh Parashar",
      "RollNo" : 101,
      "Percentage" : "80%"
   },
   {
      "Name" : "Dinkar Kad",
      "RollNo" : 201,
      "Percentage" : "70%"
   },
   {
      "Name" : "Robert",
      "RollNo" : 191,
      "Percentage" : "75%"
   },
   {
      "Name" : "Julian Joe",
      "RollNo" : 111,
      "Percentage" : "77%"
   }
]

testAngularJS

<html>
   <head>
      <title>Angular JS Includes</title>

      <style>
         table, th , td {
            border: 1px solid grey;
            border-collapse: collapse;
            padding: 5px;
         }
         table tr:nth-child(odd) {
            background-color: #f2f2f2;
         }
         table tr:nth-child(even) {
            background-color: #ffffff;
         }
      </style>
   </head>

   <body>
      <h2>AngularJS Sample Application</h2>
      <div ng-app = "" ng-controller = "studentController">

         <table>
            <tr>
               <th>Name</th>
               <th>Roll No</th>
               <th>Percentage</th>
            </tr>

            <tr ng-repeat = "student in students">
               <td>{{ student.Name }}</td>
               <td>{{ student.RollNo }}</td>
               <td>{{ student.Percentage }}</td>
            </tr>
         </table>
      </div>

      <script>
         function studentController($scope,$http) {
            var url = "/data.txt";

            $http.get(url).then( function(response) {
               $scope.students = response.data;
            });
         }
      </script>

      <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js">
      </script>

   </body>
</html>

出力

この例を実行するには、_testAngularJS_および_data.txt_ファイルをWebサーバーにデプロイする必要があります。 WebブラウザーでサーバーのURLを使用して_testAngularJS_ファイルを開き、結果を確認します。

AngularJS-ビュー

AngularJSは、単一ページ上の複数のビューを介した単一ページアプリケーションをサポートします。 これを行うために、AngularJSはng-viewおよびng-templateディレクティブ、および$ routeProviderサービスを提供しています。

ng-viewディレクティブ

ng-viewディレクティブは、構成に基づいて対応するビュー(HTMLまたはng-templateビュー)を配置できるプレースホルダーを作成するだけです。

使用法

メインモジュール内でng-viewを使用してdivを定義します。

<div ng-app = "mainApp">
   ...
   <div ng-view></div>

</div>

ng-templateディレクティブ

ng-templateディレクティブは、scriptタグを使用してHTMLビューを作成するために使用されます。 ビューにコントローラーをマップするために$ routeProviderによって使用される_id_属性が含まれています。

使用法

メインモジュール内でタイプがng-templateのスクリプトブロックを定義します。

<div ng-app = "mainApp">
   ...

   <script type = "text/ng-template" id = "addStudent">
      <h2> Add Student </h2>
      {{message}}
   </script>

</div>

$ routeProviderサービス

$ routeProviderは、URLの構成を設定し、それらを対応するHTMLページまたはng-templateにマップし、同じものを使用してコントローラーを接続する主要なサービスです。

使い方1

メインモジュール内でタイプがng-templateのスクリプトブロックを定義します。

<div ng-app = "mainApp">
   ...
   <script type = "text/ng-template" id = "addStudent">
      <h2> Add Student </h2>
      {{message}}
   </script>
</div>

使い方2

メインモジュールでスクリプトブロックを定義し、ルーティング構成を設定します。

var mainApp = angular.module("mainApp", ['ngRoute']);

mainApp.config(['$routeProvider', function($routeProvider) {
   $routeProvider

   .when('/addStudent', {
      templateUrl: 'addStudent', controller: 'AddStudentController'
   })
   .when('/viewStudents', {
      templateUrl: 'viewStudents', controller: 'ViewStudentsController'
   })
   .otherwise ({
      redirectTo: '/addStudent'
   });

}]);

上記の例では、次の点を考慮することが重要です-

  • $ routeProviderは、 '$ routeProvider’としてキーを使用して、mainAppモジュールのconfigの下の関数として定義されます。
  • $ routeProvider.whenは、「addStudent」にマップされる「/addStudent」というURLを定義します。 addStudentはメインHTMLページと同じパスに存在する必要があります。 HTMLページが定義されていない場合は、ng-templateをid = "addStudent"とともに使用する必要があります。 ng-templateを使用しました。
  • 「それ以外」は、デフォルトビューを設定するために使用されます。
  • 「コントローラー」は、ビューに対応するコントローラーを設定するために使用されます。

次の例は、上記のすべてのディレクティブの使用方法を示しています。

testAngularJS

<html>
   <head>
      <title>Angular JS Views</title>
      <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
      <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular-route.min.js">
      </script>
   </head>

   <body>
      <h2>AngularJS Sample Application</h2>
      <div ng-app = "mainApp">
         <p><a href = "#addStudent">Add Student</a></p>
         <p><a href = "#viewStudents">View Students</a></p>
         <div ng-view></div>

         <script type = "text/ng-template" id = "addStudent">
            <h2> Add Student </h2>
            {{message}}
         </script>

         <script type = "text/ng-template" id = "viewStudents">
            <h2> View Students </h2>
            {{message}}
         </script>
      </div>

      <script>
         var mainApp = angular.module("mainApp", ['ngRoute']);
         mainApp.config(['$routeProvider', function($routeProvider) {
            $routeProvider

            .when('/addStudent', {
               templateUrl: 'addStudent',
               controller: 'AddStudentController'
            })
            .when('/viewStudents', {
               templateUrl: 'viewStudents',
               controller: 'ViewStudentsController'
            })
            .otherwise({
               redirectTo: '/addStudent'
            });
         }]);
         mainApp.controller('AddStudentController', function($scope) {
            $scope.message = "This page will be used to display add student form";
         });
         mainApp.controller('ViewStudentsController', function($scope) {
            $scope.message = "This page will be used to display all the students";
         });
      </script>

   </body>
</html>

出力

ファイル_testAngularJS_をWebブラウザーで開き、結果を確認します。

AngularJS-スコープ

スコープは、コントローラーをビューに接続する特別なJavaScriptオブジェクトです。 スコープにはモデルデータが含まれます。 コントローラでは、$ scopeオブジェクトを介してモデルデータにアクセスします。

<script>
   var mainApp = angular.module("mainApp", []);

   mainApp.controller("shapeController", function($scope) {
      $scope.message = "In shape controller";
      $scope.type = "Shape";
   });
</script>

上記の例では、次の重要な点が考慮されます-

  • $ scopeは、コンストラクターの定義中にコントローラーの最初の引数として渡されます。
  • $ scope.messageと$ scope.typeは、HTMLページで使用されるモデルです。
  • コントローラーがshapeControllerであるアプリケーションモジュールに反映されるモデルに値を割り当てます。
  • $ scopeで関数を定義できます。

スコープの継承

スコープはコントローラー固有です。 ネストされたコントローラーを定義すると、子コントローラーは親コントローラーのスコープを継承します。

<script>
   var mainApp = angular.module("mainApp", []);

   mainApp.controller("shapeController", function($scope) {
      $scope.message = "In shape controller";
      $scope.type = "Shape";
   });
   mainApp.controller("circleController", function($scope) {
      $scope.message = "In circle controller";
   });

</script>

上記の例では、次の重要な点が考慮されます-

  • shapeControllerのモデルに値を割り当てます。
  • _circleController_という名前の子コントローラーのメッセージをオーバーライドします。 _circleController_という名前のコントローラーのモジュール内でメッセージが使用される場合、オーバーライドされたメッセージが使用されます。

次の例は、上記のすべてのディレクティブの使用を示しています。

testAngularJS

<html>
   <head>
      <title>Angular JS Forms</title>
   </head>

   <body>
      <h2>AngularJS Sample Application</h2>

      <div ng-app = "mainApp" ng-controller = "shapeController">
         <p>{{message}} <br/> {{type}} </p>

         <div ng-controller = "circleController">
            <p>{{message}} <br/> {{type}} </p>
         </div>

         <div ng-controller = "squareController">
            <p>{{message}} <br/> {{type}} </p>
         </div>

      </div>
      <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
      </script>

      <script>
         var mainApp = angular.module("mainApp", []);

         mainApp.controller("shapeController", function($scope) {
            $scope.message = "In shape controller";
            $scope.type = "Shape";
         });
         mainApp.controller("circleController", function($scope) {
            $scope.message = "In circle controller";
         });
         mainApp.controller("squareController", function($scope) {
            $scope.message = "In square controller";
            $scope.type = "Square";
         });

      </script>

   </body>
</html>

出力

ファイル_testAngularJS_をWebブラウザーで開き、結果を確認します。

AngularJS-サービス

AngularJSは、サービスアーキテクチャを使用した懸念の分離の概念をサポートしています。 サービスはJavaScript関数であり、特定のタスクのみを実行します。 これにより、保守およびテストが可能な個々のエンティティが作成されます。 コントローラーとフィルターは、要件に基づいてそれらを呼び出すことができます。 サービスは通常、AngularJSの依存性注入メカニズムを使用して注入されます。

AngularJSは多くの組み込みサービスを提供します。 たとえば、$ http、$ route、$ window、$ locationなど。 各サービスは、サーバーデータを取得するためにajax呼び出しを行うために$ httpが使用され、ルーティング情報を定義するために$ routeが使用されるなど、特定のタスクを担当します。 組み込みのサービスには、常に$記号が先頭に付きます。

サービスを作成するには2つの方法があります-

  • 工場 *サービス

ファクトリーメソッドの使用

このメソッドでは、最初にファクトリを定義してから、メソッドを割り当てます。

var mainApp = angular.module("mainApp", []);
mainApp.factory('MathService', function() {
   var factory = {};

   factory.multiply = function(a, b) {
      return a* b
   }

   return factory;
});

サービス方法の使用

このメソッドでは、サービスを定義してからメソッドを割り当てます。 また、すでに利用可能なサービスを注入します。

mainApp.service('CalcService', function(MathService) {
   this.square = function(a) {
      return MathService.multiply(a,a);
   }
});

次の例は、上記のすべてのディレクティブの使用を示しています-

testAngularJS

<html>
   <head>
      <title>Angular JS Services</title>
      <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
      </script>
   </head>

   <body>
      <h2>AngularJS Sample Application</h2>

      <div ng-app = "mainApp" ng-controller = "CalcController">
         <p>Enter a number: <input type = "number" ng-model = "number"/></p>
         <button ng-click = "square()">X<sup>2</sup></button>
         <p>Result: {{result}}</p>
      </div>

      <script>
         var mainApp = angular.module("mainApp", []);

         mainApp.factory('MathService', function() {
            var factory = {};

            factory.multiply = function(a, b) {
               return a * b
            }
            return factory;
         });
         mainApp.service('CalcService', function(MathService) {
            this.square = function(a) {
               return MathService.multiply(a,a);
            }
         });
         mainApp.controller('CalcController', function($scope, CalcService) {
            $scope.square = function() {
               $scope.result = CalcService.square($scope.number);
            }
         });
      </script>

   </body>
</html>

出力

ファイル_testAngularJS_をWebブラウザーで開き、結果を確認します。

AngularJS-依存性注入

依存性注入は、コンポーネント内でハードコーディングするのではなく、コンポーネントに依存関係を与えるソフトウェア設計です。 コンポーネントが依存関係を見つけるのを防ぎ、依存関係を構成可能にします。 また、コンポーネントを再利用可能、保守可能、テスト可能にするのにも役立ちます。

AngularJSは、最高の依存性注入メカニズムを提供します。 依存関係として互いに注入できる次のコアコンポーネントを提供します。

  • 工場
  • サービス
  • プロバイダ *定数

値は単純なJavaScriptオブジェクトです。これは、構成フェーズ中にコントローラーに値を渡すために必要です(構成フェーズは、AngularJSがブートストラップするときです)。

//define a module
var mainApp = angular.module("mainApp", []);

//create a value object as "defaultInput" and pass it a data.
mainApp.value("defaultInput", 5);
...

//inject the value in the controller using its name "defaultInput"
mainApp.controller('CalcController', function($scope, CalcService, defaultInput) {
   $scope.number = defaultInput;
   $scope.result = CalcService.square($scope.number);

   $scope.square = function() {
      $scope.result = CalcService.square($scope.number);
   }
});

工場

ファクトリは、値を返すために使用される関数です。 サービスまたはコントローラーが必要とするたびに、オンデマンドで値を作成します。 通常、ファクトリ関数を使用して値を計算して返します。

//define a module
var mainApp = angular.module("mainApp", []);

//create a factory "MathService" which provides a method multiply to return multiplication of two numbers
mainApp.factory('MathService', function() {
   var factory = {};

   factory.multiply = function(a, b) {
      return a* b
   }
   return factory;
});

//inject the factory "MathService" in a service to utilize the multiply method of factory.
mainApp.service('CalcService', function(MathService) {
   this.square = function(a) {
      return MathService.multiply(a,a);
   }
});
...

サービス

サービスは、特定のタスクを実行するための一連の関数を含むシングルトンJavaScriptオブジェクトです。 サービスはservice()関数を使用して定義され、コントローラーに挿入されます。

//define a module
var mainApp = angular.module("mainApp", []);
...

//create a service which defines a method square to return square of a number.
mainApp.service('CalcService', function(MathService) {
   this.square = function(a) {
      return MathService.multiply(a,a);
   }
});

//inject the service "CalcService" into the controller
mainApp.controller('CalcController', function($scope, CalcService, defaultInput) {
   $scope.number = defaultInput;
   $scope.result = CalcService.square($scope.number);

   $scope.square = function() {
      $scope.result = CalcService.square($scope.number);
   }
});

プロバイダ

プロバイダーは、サービス、ファクトリなどを作成するために、AngularJSによって内部的に使用されます。 構成フェーズ中。 次のスクリプトを使用して、前に作成したMathServiceを作成できます。 プロバイダーは、値/サービス/工場を返すために使用されるget()メソッドを持つ特別なファクトリーメソッドです。

//define a module
var mainApp = angular.module("mainApp", []);
...

//create a service using provider which defines a method square to return square of a number.
mainApp.config(function($provide) {
   $provide.provider('MathService', function() {
      this.$get = function() {
         var factory = {};

         factory.multiply = function(a, b) {
            return a *b;
         }
         return factory;
      };
   });
});

定数

定数は、構成フェーズで値を使用できないという事実を考慮して、構成フェーズで値を渡すために使用されます。

mainApp.constant("configParam", "constant value");

次の例は、上記のすべてのディレクティブの使用を示しています-

testAngularJS

<html>
   <head>
      <title>AngularJS Dependency Injection</title>
   </head>

   <body>
      <h2>AngularJS Sample Application</h2>

      <div ng-app = "mainApp" ng-controller = "CalcController">
         <p>Enter a number: <input type = "number" ng-model = "number"/></p>
         <button ng-click = "square()">X<sup>2</sup></button>
         <p>Result: {{result}}</p>
      </div>

      <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
      </script>

      <script>
         var mainApp = angular.module("mainApp", []);

         mainApp.config(function($provide) {
            $provide.provider('MathService', function() {
               this.$get = function() {
                  var factory = {};

                  factory.multiply = function(a, b) {
                     return a* b;
                  }
                  return factory;
               };
            });
         });

         mainApp.value("defaultInput", 5);

         mainApp.factory('MathService', function() {
            var factory = {};

            factory.multiply = function(a, b) {
               return a * b;
            }
            return factory;
         });
         mainApp.service('CalcService', function(MathService) {
            this.square = function(a) {
               return MathService.multiply(a,a);
            }
         });
         mainApp.controller('CalcController', function($scope, CalcService, defaultInput) {
            $scope.number = defaultInput;
            $scope.result = CalcService.square($scope.number);

            $scope.square = function() {
               $scope.result = CalcService.square($scope.number);
            }
         });
      </script>

   </body>
</html>

出力

Webブラウザーで_testAngularJS_を開き、結果を確認します。

AngularJS-カスタムディレクティブ

AngularJSでは、HTMLの機能を拡張するためにカスタムディレクティブが使用されます。 カスタムディレクティブは、「ディレクティブ」関数を使用して定義されます。 カスタムディレクティブは、アクティブ化された要素を単に置き換えるだけです。 ブートストラップ中のAngularJSアプリケーションは、一致する要素を見つけ、カスタムディレクティブのcompile()メソッドを使用して1回アクティビティを実行し、ディレクティブのスコープに基づいてカスタムディレクティブのlink()メソッドを使用して要素を処理します。 AngularJSは、次のタイプの要素のカスタムディレクティブの作成をサポートします。

  • 要素ディレクティブ-一致する要素が見つかると、ディレクティブがアクティブになります。
  • 属性-一致する属性が検出されると、ディレクティブがアクティブになります。
  • CSS -一致するCSSスタイルが検出されると、ディレクティブがアクティブになります。
  • コメント-一致するコメントが検出されると、ディレクティブがアクティブになります。

カスタムディレクティブについて

カスタムhtmlタグを定義します。

<student name = "Mahesh"></student><br/>
<student name = "Piyush"></student>

上記のカスタムhtmlタグを処理するカスタムディレクティブを定義します。

var mainApp = angular.module("mainApp", []);

//Create a directive, first parameter is the html element to be attached.
//We are attaching student html tag.
//This directive will be activated as soon as any student element is encountered in html

mainApp.directive('student', function() {
  //define the directive object
   var directive = {};

  //restrict = E, signifies that directive is Element directive
   directive.restrict = 'E';

  //template replaces the complete element with its text.
   directive.template = "Student: <b>{{student.name}}</b> ,
      Roll No: <b>{{student.rollno}}</b>";

  //scope is used to distinguish each student element based on criteria.
   directive.scope = {
      student : "=name"
   }

  //compile is called during application initialization. AngularJS calls
      it once when html page is loaded.

   directive.compile = function(element, attributes) {
      element.css("border", "1px solid #cccccc");

     //linkFunction is linked with each element with scope to get the element specific data.
      var linkFunction = function($scope, element, attributes) {
         elementl("Student: <b>"+$scope.student.name +"</b> ,
            Roll No: <b>"+$scope.student.rollno+"</b><br/>");
         element.css("background-color", "#ff00ff");
      }
      return linkFunction;
   }

   return directive;
});

コントローラーを定義して、ディレクティブのスコープを更新します。 ここでは、name属性の値をスコープの子として使用しています。

mainApp.controller('StudentController', function($scope) {
   $scope.Mahesh = {};
   $scope.Mahesh.name = "Mahesh Parashar";
   $scope.Mahesh.rollno  = 1;

   $scope.Piyush = {};
   $scope.Piyush.name = "Piyush Parashar";
   $scope.Piyush.rollno  = 2;
});

<html>
   <head>
      <title>Angular JS Custom Directives</title>
   </head>

   <body>
      <h2>AngularJS Sample Application</h2>

      <div ng-app = "mainApp" ng-controller = "StudentController">
         <student name = "Mahesh"></student><br/>
         <student name = "Piyush"></student>
      </div>

      <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
      </script>

      <script>
         var mainApp = angular.module("mainApp", []);

         mainApp.directive('student', function() {
            var directive = {};
            directive.restrict = 'E';
            directive.template = "Student: <b>{{student.name}}</b> ,
               Roll No: <b>{{student.rollno}}</b>";

            directive.scope = {
               student : "=name"
            }
            directive.compile = function(element, attributes) {
               element.css("border", "1px solid #cccccc");

               var linkFunction = function($scope, element, attributes) {
                  elementl("Student: <b>"+$scope.student.name +"</b> ,
                     Roll No: <b>"+$scope.student.rollno+"</b><br/>");
                  element.css("background-color", "#ff00ff");
               }
               return linkFunction;
            }

            return directive;
         });
         mainApp.controller('StudentController', function($scope) {
            $scope.Mahesh = {};
            $scope.Mahesh.name = "Mahesh Parashar";
            $scope.Mahesh.rollno  = 1;

            $scope.Piyush = {};
            $scope.Piyush.name = "Piyush Parashar";
            $scope.Piyush.rollno  = 2;
         });
      </script>

   </body>
</html>

出力

Webブラウザーで_textAngularJS_を開きます。 結果をご覧ください。

AngularJS-国際化

AngularJSは、通貨、日付、数値の3種類のフィルターの組み込み国際化をサポートしています。 国のロケールに応じて、対応するjavaスクリプトを組み込むだけです。 デフォルトでは、ブラウザのロケールが考慮されます。 たとえば、デンマーク語のロケールの場合、次のスクリプトを使用します-

<script src = "https://code.angularjs.org/1.2.5/i18n/angular-locale_da-dk.js">
</script>

デンマーク語ロケールの使用例

testAngularJS

<html>
   <head>
      <title>Angular JS Forms</title>
   </head>

   <body>
      <h2>AngularJS Sample Application</h2>

      <div ng-app = "mainApp" ng-controller = "StudentController">
         {{fees | currency }}  <br/><br/>
         {{admissiondate | date }}  <br/><br/>
         {{rollno | number }}
      </div>

      <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
      </script>
      <script src = "https://code.angularjs.org/1.3.14/i18n/angular-locale_da-dk.js">
      </script>

      <script>
         var mainApp = angular.module("mainApp", []);

         mainApp.controller('StudentController', function($scope) {
            $scope.fees = 100;
            $scope.admissiondate  = new Date();
            $scope.rollno = 123.45;
         });
      </script>

   </body>
</html>

出力

ファイル_testAngularJS_をWebブラウザーで開き、結果を確認します。

ブラウザロケールを使用した例

testAngularJS

<html>
   <head>
      <title>Angular JS Forms</title>
   </head>

   <body>
      <h2>AngularJS Sample Application</h2>

      <div ng-app = "mainApp" ng-controller = "StudentController">
         {{fees | currency }}  <br/><br/>
         {{admissiondate | date }}  <br/><br/>
         {{rollno | number }}
      </div>

      <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
      </script>
      <!-- <script src = "https://code.angularjs.org/1.3.14/i18n/angular-locale_da-dk.js">
      </script> -->

      <script>
         var mainApp = angular.module("mainApp", []);

         mainApp.controller('StudentController', function($scope) {
            $scope.fees = 100;
            $scope.admissiondate  = new Date();
            $scope.rollno = 123.45;
         });
      </script>

   </body>
</html>

出力

ファイル_testAngularJS_をWebブラウザーで開き、結果を確認します。

AngularJS-Todoアプリケーション

Todoアプリの例を提供しています。 このアプリを開発するために、HTML、CSS、AngularJSを使用しました。 angular-route.jsやbase.jsなどのjavascriptが含まれています。

ソースコードはlink:/angularjs/src/todo/todo.zip [こちら]から入手できます。

AngularJS-メモ帳アプリケーション

メモ帳アプリの例を提供しています。 このアプリを開発するために、HTML、CSS、AngularJSを使用しました。 myNoteApp.jsやmyNoteCtrl.jsなどのjavascriptが含まれています。

ソースコードはlink:/angularjs/src/notepad/notepad.zip [こちら]から入手できます。

AngularJS-ブートストラップアプリケーション

Bootstrapアプリの例を提供しています。 このアプリを開発するために、HTML、CSS、AngularJSを使用しました。

ソースコードはlink:/angularjs/src/bootstrap.zipから入手できます[こちら]

AngularJS-ログインアプリケーション

ログインアプリの例を提供しています。 このアプリを開発するために、HTML、CSS、AngularJSを使用しました。

ソースコードはlink:/angularjs/src/login/login.zip [こちら]から入手できます。

AngularJS-ファイルのアップロード

ファイルのアップロードの例を提供しています。 このアプリを開発するために、HTML、CSS、AngularJSを使用しました。 次の例は、AngularJSを使用してファイルをアップロードする方法を示しています。

<html>
   <head>
      <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
      </script>
   </head>

   <body ng-app = "myApp">

      <div ng-controller = "myCtrl">
         <input type = "file" file-model = "myFile"/>
         <button ng-click = "uploadFile()">upload me</button>
      </div>

      <script>
         var myApp = angular.module('myApp', []);

         myApp.directive('fileModel', ['$parse', function ($parse) {
            return {
               restrict: 'A',
               link: function(scope, element, attrs) {
                  var model = $parse(attrs.fileModel);
                  var modelSetter = model.assign;

                  element.bind('change', function() {
                     scope.$apply(function() {
                        modelSetter(scope, element[0].files[0]);
                     });
                  });
               }
            };
         }]);
         myApp.service('fileUpload', ['$https:', function ($https:) {
            this.uploadFileToUrl = function(file, uploadUrl) {
               var fd = new FormData();
               fd.append('file', file);

               $https:.post(uploadUrl, fd, {
                  transformRequest: angular.identity,
                  headers: {'Content-Type': undefined}
               })
               .success(function() {
               })
               .error(function() {
               });
            }
         }]);
         myApp.controller('myCtrl', ['$scope', 'fileUpload', function($scope, fileUpload) {
            $scope.uploadFile = function() {

               var file = $scope.myFile;
               console.log('file is ' );
               console.dir(file);
               var uploadUrl = "/fileUpload";
               fileUpload.uploadFileToUrl(file, uploadUrl);
            };
         }]);
      </script>

   </body>
</html>

結果

上記の保存済みコードファイルをWebブラウザーで開きます。 結果をご覧ください。

AngularJS-インラインアプリケーション

インラインアプリの例を提供しています。 このアプリを開発するために、HTML、CSS、AngularJSを使用しました。 このアプリを使用して、以下に示すようにインラインテキストを変更できます-

ソースコードはlink:/angularjs/src/todo/todo.zip [こちら]から入手できます。

AngularJS-ナビゲーションメニュー

Navメニューアプリの例を提供しています。 このアプリを開発するために、HTML、CSS、AngularJSを使用しました。

ソースコードはlink:/angularjs/src/nav/nav.zipから入手できます[こちら]

AngularJS-メニューの切り替え

Switchメニューの例を提供しています。 このアプリを開発するために、HTML、CSS、AngularJSを使用しました。

ソースコードはlink:/angularjs/src/switch/switch.zipから入手できます[こちら]

AngularJS-注文フォーム

注文フォームの例を提供しています。 このアプリを開発するために、HTML、CSS、Script.js、AngularJSを使用しました。

ソースコードはlink:/angularjs/src/order/order.zipから入手できます[こちら]

AngularJS-[検索]タブ

[検索]タブの例を提供しています。 このアプリを開発するために、HTML、CSS、AngularJSを使用しました。

ソースコードはlink:/angularjs/src/search/search.zipから入手できます[こちら]

AngularJS-アプリケーションをドラッグ

ドラッグアプリの例を提供しています。 このアプリを開発するために、HTML、CSS、ngDraggable.js、AngularJSを使用しました。

ソースコードはlink:/angularjs/src/drag/drag.zip [こちら]から入手できます。

AngularJS-カートアプリケーション

Cartアプリの例を提供しています。 このアプリを開発するために、HTML、CSS、AngularJSを使用しました。

ソースコードはlink:/angularjs/src/cart/src/cart.zipから入手できます[こちら]

AngularJS-アプリケーションの翻訳

翻訳アプリの例を提供しています。 このアプリを開発するために、HTML、CSS、translate.js、AngularJSを使用しました。

ソースコードはlink:/angularjs/src/translate/translate.zipから入手できます[こちら]

AngularJS-チャートアプリケーション

Chartアプリの例を提供しています。 このアプリを開発するために、HTML、CSS、chat.js、AngularJSを使用しました。

ソースコードはlink:/angularjs/src/chart/chart.zip [こちら]から入手できます。

AngularJS-マップアプリケーション

Googleマップアプリの例を提供しています。 このアプリを開発するために、HTML、CSS、Maps、AngularJSを使用しました。

ソースコードはlink:/angularjs/src/map/map.zipから入手できます[こちら]

AngularJS-アプリケーションの共有

共有アプリの例を提供しています。 このアプリを開発するために、HTML、CSS social.js、AngularJSを使用しました。

ソースコードはlink:/angularjs/src/share/share.zipから入手できます[こちら]

AngularJS-天気予報アプリケーション

Weatherアプリの例を提供しています。 このアプリを開発するために、HTML、CSS、weather.js、AngularJSを使用しました。

ソースコードはlink:/angularjs/src/temp/temp.zipから入手できます[こちら]

AngularJS-タイマーアプリケーション

タイマーアプリの例を提供しています。 このアプリを開発するために、HTML、CSS、Timer.js、AngularJSを使用しました。

ソースコードはlink:/angularjs/src/timer/timer.zip [こちら]から入手できます。

AngularJS-リーフレットアプリケーション

リーフレットアプリの例を提供しています。 このアプリを開発するために、HTML、CSS、リーフレット、AngularJSを使用しました。

ソースコードはlink:/angularjs/src/leaflet/leaflet.zip [こちら]から入手できます。

AngularJS-LastFmアプリケーション

Lastfmアプリの例を提供しています。 このアプリを開発するために、HTML、CSS、LastFm、AngularJSを使用しました。

ソースコードはlink:/angularjs/src/lastfm/lastfm.zip [こちら]から入手できます。 Angularjs-questions-answers