それがどのように機能するかを説明しようとします:
編集:ライブデモ
html
これがあなたの簡素化された選択です。
<select ng-options="item as item.text for item in foodCategories"
ng-model="foodCategory"
ng-required="true"
ng-change="changeFoodCategory()">
</select>
ディレクティブは、選択した要素をng-options
自動的に埋めます。コレクション内のコントローラーと foreachから変数をoption
取得し、表示されるラベルとしてプロパティを使用します ( item option {{item.text}} ng-model id` 選択したオプションの値。foodCategories
$scope
item
text
<option>{{item.text}}</option>') and it will select the whole object
as the value of the selected
. You could also refer to a property as the value like (
). Then your
would be set to the
ディレクティブは、選択したオプションの値を保持するコントローラーng-model
の変数に対応します。$scope
ディレクティブng-required
を使用すると、値が選択されているかどうかを確認できます。フォームを使用している場合は、フィールドが有効かどうかを確認できますformName.ngModelName.$valid
。フォーム検証の詳細については、ドキュメントを参照してください。
ディレクティブng-change
を使用すると、選択したオプションが変更されるたびに関数を実行できます。変数をこの関数にパラメーターとして渡すか、コントローラー内でng-model
変数を呼び出すことができます。$scope
デフォルト値が設定されていない場合、angular は、オプションが選択されると削除される空のオプションを追加します。
ディレクティブを使用して最初のオプションを選択しましたが、コントローラーの変数を希望するデフォルト値またはなしにng-init
設定できることを知っています。ng-model
js
ここでは、非同期リクエストを実行している場合に promise を返すことで、データベース サービスをシミュレートしようとしました。この$q
サービスを使用して promise を作成$timeout
し、データベースへの呼び出しを偽装しました。
myApp.factory('DbFoodCategories', function($q, $timeout) {
var foodCategories = [
{ id: 1, text: "Veggies", value: 100 },
{ id: 2, text: "Fruits", value: 50 },
{ id: 3, text: "Pasta", value: 200 },
{ id: 4, text: "Cereals", value: 250 },
{ id: 5, text: "Milk", value: 150 }
];
return {
get: function() {
var deferred = $q.defer();
// Your call to the database in place of the $timeout
$timeout(function() {
var chance = Math.random() > 0.25;
if (chance) {
// if the call is successfull, return data to controller
deferred.resolve(foodCategories);
}
else {
// if the call failed, return an error message
deferred.reject("Error");
}
}, 500);
/* // your code
_context.onReady({
success: function() {
deferred.resolve(_contect.FoodGroup);
},
error: function (error){
deferred.reject("Error");
}
});
*/
// return a promise that we will send a result soon back to the controller, but not now
return deferred.promise;
},
insert: function(item) {
/* ... */
},
update: function(item) {
/* ... */
},
remove: function(item) {
/* ... */
}
};
});
コントローラーで、ビューで使用される変数を設定します。そのため、サービスを呼び出してDbFoodCategories
データを にロードし、選択したオプションの設定に使用される$scope.foodCategories
デフォルト値を$scope.foodCategory
に設定できます。
myApp.controller('FoodSelection',function($scope, DbFoodCategories){
DbFoodCategories.get().then(
// the callback if the request was successfull
function (response) {
$scope.foodCategories = response; //response is the data we sent from the service
},
// the callback if an error occured
function (response) {
// response is the error message we set in the service
// do something like display the message
}
);
// $scope.foodCategory = defaultValue;
$scope.changeFoodCategory = function() {
alert($scope.foodCatagory.value);
}
});
これが、何が起こっているのかをより詳細に理解するのに役立つことを願っています!