LoginSignup
5
7

More than 5 years have passed since last update.

angularで覚えておいたほうがいい便利なもの

Last updated at Posted at 2017-01-13

◼配列操作

1. angular forEachを使う

controller.js
var files = [];
angular.forEach($scope.photos, function(photo, key) {
  this.push({ file_id: photo.file_id, url: photo.file.url, title: photo.title });
}, files);

◼データバインド

バインドがうまくいかないときは$apply様を使う

ng-click$time等を使わないケースや
ng-modelng-bindを使用していても
angularと関係ないものを使っている場合などには(jQueryやプラグイン)datepicker etc...
「即時反映されない。」($digestのタイミングがくるまで待機)

これを即時反映させたいときには、$applyを使うとバインドがうまくいきます。

controller.js
$scope.$apply(function() {
  //実行内容
});
controller.js
$scope.$apply($scope.setParams());

◼金額を日本円で表記したい場合

  • ※ angular-i18n モジュールを読み込みんでいる状態が前提です。
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/angular-i18n/1.2.10/angular-locale_ja-jp.min.js"></script>
mainController.js
$scope.price = 4000;

numberフィルターを使用する

index.html
{{ price|number }}
>>> 4,000.00

小数点以下を切り捨てする

index.html
{{ price|number:0 }}
>>> 4,000

参考: 公式ドキュメント: http://js.studio-kingdom.com/angularjs/ng_filter/number

◼セレクトボックスの作成

やり方は二通りあります。

1. ng-repeatを使う

controller.js

/**
 * 1から100の配列を作成
 */
$scope.quantities = function () {
  var quantities = [];
  for(var i=1; i<=100; i++) {
    quantities.push(i);
  }
  return quantities;
};
index.mthaml
%select(name="item_quantity" ng-model="item.quantity" ng-required="true" dir="rtl")
  %option(value="" dir="opt") タップして選択
  %option(ng-repeat="num in quantities()" ng-value="num" ng-bind="num")

2. ng-optionsを使う

連想配列、optionのkeyとvalueで値を変えたい場合

controller.js
$scope.prefs = ['北海道', '東京都', '神奈川県','沖縄'];
index.mthaml
%select(name="prefId" ng-model="prefId" ng-options="num as key for (num, key) in prefs" dir="rtl")
  %option(value="" dir="opt") タップして選択

◼ ng-epeatを使うときに$$hashkeyでエラーがでる

api等でjsonデータを取得した場合、$$hashkeyというキーを持っているとng-repeatができないというエラーがでます。

track byを使うことでこれを回避することができます。

index.mthaml
%div(ng-repeat="item in estimate.json_data track by $index")

◼スマートフォンのキーボードあれこれ

追記: 2017/01/26

数字のみでバリデーション

<input type="text" ng-pattern="/^[0-9]+$/">

数字と小数点のみでバリデーション

<input type="text" ng-pattern="/^\\d+(?:\\.\\d+)?$/">

キーボードを数字のみにする

<input type="text" pattern="\\d*">
5
7
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
7