javascript - Angularjs Dropdown OnChange Selected Text and Value -
i new angularjs
, trying selected text , value dropdown
. followed lot of tutorials still unable there. selectedvalue
, selectedtext
undefined
. below code:
html:
<div ng-app="selectapp"> <div ng-controller="selectcontroller"> <select name="category-group" id="categorygroup" class="form-control" ng-model="itemselected" ng-change="oncategorychange(itemselected)"> <option value="0">select category...</option> <option ng-repeat="category in categories" value="{{category.id}}" ng-disabled="category.disabled" ng-class="{'maincategory' : category.disabled}"> {{category.name}} </option> </select> </div>
js:
'use strict'; var app = angular.module('selectapp', [ ]); app.controller('selectcontroller', ['$scope', '$window', function ($scope, $window) { $scope.categories = [ { id: 1, name: "- vehicles -", disabled: true }, { id: 2, name: "cars" }, { id: 3, name: "commercial vehicles", disabled: false }, { id: 4, name: "motorcycles", disabled: false }, { id: 5, name: "car & motorcycle equipment", disabled: false }, { id: 6, name: "boats", disabled: false }, { id: 7, name: "other vehicles", disabled: false }, { id: 8, name: "- house , children -", disabled: true }, { id: 9, name: "appliances", disabled: false }, { id: 10, name: "inside", disabled: false }, { id: 11, name: "games , clothing", disabled: false }, { id: 12, name: "garden", disabled: false } ]; $scope.oncategorychange = function () { $window.alert("selected value: " + $scope.itemselected.id + "\nselected text: " + $scope.itemselected.name); }; }]);
and 1 more thing, have defined first item select category...
why first item in dropdown empty.
below fiddle sample. http://jsfiddle.net/qgmz7/136/
that's because, model itemselected
captures current value of select drop down nothing value
attribute of option
element. have
<option ng-repeat="category in categories" value="{{category.id}}">
in code, in rendered version, you'll
<option ng-repeat="category in categories" value="0">
but you're expecting itemselected
category object , attempt query id
or other property return undefined
.
you can use ng-options
group by
little bit of change data or can use normal ng-repeat
, selectedindex , lookup category object categories list using index. showcasing first approach here.
html
<select name="category-group" id="categorygroup" ng-model="itemselected" ng-change="oncategorychange(itemselected)" ng-options="category.name group category.group category in categories"> </select>
updated data
$scope.categories = [ { id: 0, name: "select category..."}, { id: 1, name: "cars", group : "- vehicles -" }, { id: 2, name: "commercial vehicles", group : "- vehicles -" }, { id: 3, name: "motorcycles", group : "- vehicles -" } ]; $scope.itemselected = $scope.categories[0];
instead of disabled property, can add group
property can used in group by
.
here' updated fiddle illustrate idea.
Comments
Post a Comment