LoginSignup
5
5

More than 5 years have passed since last update.

AngularJSに挑戦!入門 その5

Last updated at Posted at 2014-11-05

はじめに

AngularJSには、serviceというものがあります。
アプリケーションの共通部品として利用できるようにするものです。
1度挑戦してみます。

Serviceの実装

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


MyApp.service('MyAppSevrices', [function () {

    this.plus = function (x, y) {
        return (x + y);
    }

    this.minus = function (x, y) {
        return (x - y);
    }

    this.multiply = function (x, y) {
        return (x * y);
    }

    this.divide = function (x, y) {
        return (x / y);
    }
}]);

足し算・引き算・掛け算・割り算のサービスです。
サービス名を指定して、各関数を作成します。

Controllerの実装

serviceSample.js
MyApp.controller('ServiceCtrl', function ($scope, MyAppSevrices) {
    $scope.plus = function() {
        return MyAppSevrices.plus(parseInt($scope.x), parseInt($scope.y));
    }

    $scope.minus = function() {
        return MyAppSevrices.minus(parseInt($scope.x), parseInt($scope.y));
    }

    $scope.multiply = function() {
        return MyAppSevrices.multiply(parseInt($scope.x), parseInt($scope.y));
    }

    $scope.divide = function() {
        return MyAppSevrices.divide(parseInt($scope.x), parseInt($scope.y));
    }
});

コントローラーでサービスを呼び出します。
MyApp.controller('ServiceCtrl', function ($scope, MyAppSevrices) {
が今までと違う点です。いままでは、$scopeのみを渡していましたが、
サービスを利用するときは、サービス名を指定します。

Viewの実装

serviceSample.html
<html>
<head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css">
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.1/angular.min.js"></script>
    <script type="text/javascript" src="serviceSample.js"></script>
    <title>serviceSample</title>
</head>
<body ng-app="MyApp">
    <div class="container">
        <div class="jumbotron">
            <h2>serviceSample!</h2>
        </div>
        <div ng-controller="ServiceCtrl">
            <input ng-model="x"><input ng-model="y">
            <div class="bg-info">
                <p>足し算: {{plus()}}</p>
                <p>引き算: {{minus()}}</p>
                <p>掛け算: {{multiply()}}</p>
                <p>割り算: {{divide()}}</p>
            </div>
        </div>
    </div>
</body>
</html>

今まで通りの作成で問題ありません。
ng-modelにxとyを設定しています。
両方に数値を指定すれば、それぞれ計算がされます。

おわりに

共通部品を作成することは、アプリケーションを作るうえで必須のことだと思います。
簡単な例でしたが、基本を押さえるのに適した例だと思います。
いろいろなサービスを作成していきましょう。

5
5
0

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