2014年11月13日木曜日

AngularJsを使ってみる―Directiveの分割―

別のモジュールを作って、Directiveを分割してみます。

前提:表示する大本のページを"index.html"、読み込むAngularソースを"sampel-app.js"、新しく作成するモジュールを含んだソースを"new-sample-app.js"であるとします。

①new-sample-app.jsに、次のような新しいモジュールを記述します。

(function() {
  angular.module("new-sample-app", [])
  
  .directive("productDescription", function() {
    return {
      restrict: 'E',
      templateUrl: "something.html"
    };
  });
 })();

②sampl-app.jsに、依存関係を追加します。依存関係がない場合は空白にしていた部分ですが、今回は新しいモジュール名を追加しておきます。

angular.module('sample-app', ["new-sample-app"])
・・・

③index.htmlのヘッダー内で、new-sample-app.jsを読み込みます。htmlタグ内で読み込んでいたng-appの指定を変更する必要はありません。

今回であれば、<html ng-app="sample-app">となっているはずです。

<head>
  <script type="text/javascript" src="angular.min.js"></script>
  <script type="text/javascript" src="sample-app.js"></script>
  <script type="text/javascript" src="new-sample-app.js"></script>
</head>

0 件のコメント:

コメントを投稿