AngularJS/OnsenUI:javascriptでランダムな配列を生成するコードのメモ

Published on:
Last updated:

This post is also available in: 日本語 (Japanese)

AngularJS/OnsenUIの概念に慣れていなくて軽く苦労したのでメモ。
開発環境はMonacaで、OnsenUIを使っています。

やりたかったこと

AngularJS-medium

AngularJS-medium

OnsenUIを使って同一ページ内にリスト(ons-list-item)とテキストボックスを表示する。
リスト(ons-list-item)にはlocalStorage(var data)からランダムに選びだされた3つの要素を表示する。
で、そのリストの内容に対してのコメントをテキストボックス入力する。

改善したい点は、テキストボックスに文字を入力するとリアルタイムにリストの内容が変更されること。

改善する前のランダムな配列を生成するコード

一番最初は、AngularJSのng-repeat filterでランダムな配列を生成しようとしました。

すると、別のイベント(テキストボックスに入力するなど)が起こった時に、リアルタイムでリスト(ons-list-item)のfilter(orderBy:RandomSelect)が働いてしまいました。

サンプルコードのような場合だと、(同じページ内の)テキストボックスに入力するとそれに呼応してリアルタイムにリスト(ons-list-item)内の{{memo.text}}の内容がランダムに生成されてしまいます。

<!-- サンプルなのでこのままでは動きません。 -->
<!-- HTML -->
<secton ng-controller="Sample">
	<ons-list-item ng-repeat="memo in memos|orderBy:RandomSelect|limitTo:3" ng-click="">
		{{memo.text}}
	</ons-list-item>
</secton>

<!-- javascript -->
var data = [
	{text: 'sample 1'},
	{text: 'sample 2'}
];

function Sample($scope, data) {
	$scope.memos = data;
	//ランダムで表示 
	$scope.RandomSelect = function() {
		return Math.random();
	};
}    

改善したランダムな配列を生成するコード

最初はjQuery Mobileで実装しようと考えました。
しかし、AngularJSとjQuery Mobileは併用可能らしいのですが、なぜか不具合が出たので今回は諦めて、下記のようなコードでランダムな配列を実現しました。

<!-- サンプルなのでこのままでは動きません。 -->
<!-- HTML -->
<secton ng-controller="Sample">
	<ons-list-item ng-repeat="memo in memos|limitTo:3" ng-click="">
		{{memo.text}}
	</ons-list-item>
</secton>

<!-- javascript -->
var data = [
	{text: 'sample 1'},
	{text: 'sample 2'}
];

function Sample($scope, data) {
	$scope.memos = data;
	shuffle($scope.memos);

	// Random Generate Function
	function shuffle(array) {
		array.sort(function() {
			return Math.random() - 0.5;
		});
	}
};

AngularJS+OnsenUIのおすすめ本。
クラウドでできるHTML5ハイブリッドアプリ開発 Cordova/Onsen UIで作るiOS/Android両対応アプリ (Monaca公式ガイドブック)

About
Kuniyoshi Takemoto is the founder of Amelt.net LLC, and editor of this blog(www.amelt.net).Learn more and follow me on LinkedIn.