LoginSignup
5
5

More than 5 years have passed since last update.

AngularJSに挑戦!入門 その3

Last updated at Posted at 2014-11-03

はじめに

前回の記事では、詳しく触れなかった$scope変数について少し触れてみます。
スコープ変数は、アプリケーションのモデルを参照するオブジェクトです。
特徴として、Modelの変更を見張るAPIを有してます。
また、評価対象の式 に対してコンテキストを提供します。

難しいことかもしれませんが、簡単に言うと、
・さまざまな関数を使用できる。
・プロパティーの追加・変更・削除が可能。
・プロパティーをViewで参照できるようにする

と言ったところです。本来は、もっといろいろありますが、まずはこれを覚えれば大丈夫と思います。

実際に使ってみる

Sample05.js
var MyApp = angular.module('MyApp', []);

MyApp.controller('SampleCtrl', ['$scope', function ($scope) {
    $scope.message = "Hello My Message!";

    $scope.plus = function(value1, value2) {
        return (parseInt(value1) + parseInt(value2));
    }
}]);

$scope.messageは、値を設定しているだけのプロパティーです。
$scope.plusは、関数の戻り値を返してます。単純な足し算です。

では、Viewを作成します。

Sample05.html
<html>
<head>
    <meta charset="utf-8">
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css">
    <script type="text/javascript" src="Sample05.js"></script>
    <title>$scope!</title>
</head>
<body ng-app="MyApp">
    <div class="container">
        <div ng-controller="SampleCtrl">
            <div class="bg-primary">
                <p>{{message}}</p>
            </div>
            <div class="bg-info">
                <input type="text" ng-model="value1"> + <input type="text" ng-model="value2"> = {{plus(value1,value2)}}
            </div>
        </div>
    </div>
</body>
</html>

案外簡単に作成できました。

おわりに

このあたりことは、AngularJSでは基本中の基本です。
まだ、簡単なアプリケーションなので、しっかりと理解しましょう。
私も頑張って理解しているつもりです。

5
5
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5