VueJS access model from method - javascript

In VueJS I am setting model data based on user actions. I want to access the model from a method to update an element.
In the code below, when the user changes the first select list, I want to update the second select list to show the id property of the first list. As it is the upper list works OK but the lower list id property is not updated on upper list change:
<html lang="en">
<head>
<meta charset="utf-8">
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.2.1/vue.js"></script>
</head>
<body>
<div id="editor">
<form id="query" methods="GET">
<div id="form_container" class="row">
<div class="form-group">
<label for="choice-selector">Choices</label>
<select class="form-control" id="choice-selector" v-model="choice_id" v-on:change="refreshOptions">
<option v-for="item in choices" v-bind:value="item.id">
{{ item.name }}
</option>
</select>
<span>Current choice id: {{ choice_id }}</span>
<br>
<label for="option-selector">Options</label>
<select class="form-control" id="option-selector" v-model="option_id" >
<option v-for="item in options" v-bind:value="item.id">
{{ item.name }}
</option>
</select>
<span>Current option id: {{ option_id }}</span>
</div>
</div>
</div>
<script>
let index = 0;
new Vue({
el: '#editor',
data: {
choice_id: '1',
choices: [
{ id: '1', name: 'Choice A' },
{ id: '2', name: 'Choice B' },
{ id: '3', name: 'Choice C' }
],
option_id: '1',
options: [
]
},
ready: function startFetch() {
this.refreshOptions();
},
methods: {
refreshOptions: function refreshOptionList() {
console.log(">>refreshOptionList() index:" + index);
const vm = this;
const newOptions = [{ id: index, name: 'Option based on choices list id: ' + vm.choice_id }];
vm.$set('options', newOptions);
index += 1;
}
},
});
</script>
</body>
</html>
Any ideas?

In Vue 2.x vm.$set is an alias for Vue.set and it takes 3 parameters: target, key and value so you should use it like this:
vm.$set(this, 'options', newOptions);
Or you can just assign newOptions to this.options
this.options = newOptions;
Working example: https://plnkr.co/edit/lFDm7wxb56h81EAwuUNc

Related

Vuejs rendering select dropdown based on first choice in first drop down

I have two drop-down menus. Depending on the choice of the first drop-down the choices of the second need to be filtered and displayed. The first dropdown has a RoomID value that is used to filter an array of objects for the second drop-down menu. When I select a Room in the first dropdown the console log shows the correct data for the second dropdown. however, it is not rendering in the Html. I am not sure why this is not working
Html:
<div id="reports-menu" class="myTextColor1 pl-10">
<div class="row">
<div class="input-field col s12">
<select v-model="selectedRoomID">
<option disabled selected>Rooms</option>
<option v-for="room in rooms" v-bind:value="room.RoomID">{{room.Room}}</option>
</select>
<label>Room:</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<select v-model="selectedTopicID">
<option disabled selected>Topics</option>
<option v-for="option in selectedRoom" v-bind:value="option.TopicID">{{option.Topic}}</option>
</select>
<label>Topic:</label>
</div>
</div>
</div>
JS:
var data = <%=return_message%>;
let arrRooms = _.uniqBy(data, function (e) {
return e.Room;
});
let arrTopics = _.uniqBy(data, function (e) {
return e.Topic;
});
let arrDps = _.uniqBy(data, function (e) {
return e.DiscussionPoint;
});
document.addEventListener('DOMContentLoaded', function() {
var elems = document.querySelectorAll('select');
var instances = M.FormSelect.init(elems, {});
});
var chatReportsMenuComponent = new Vue({
el: "#reports-menu",
created: function () {
document.getElementById("reports-menu").style.display = "block";
//GET TOPIC INFO - PASS TOPIC PARAM;
this.initialize();
},
data: {
selectedRoomID: undefined,
rooms:arrRooms,
selectedTopicID: undefined,
topics:arrTopics,
dps:arrDps
},
methods: {
initialize: function () {
var self = this;
}
},
computed:{
selectedRoom: function(){
var filteredTopics = _.filter(arrTopics,{'RoomID': this.selectedRoomID})
console.log("Filterd Topics: ", filteredTopics)
return filteredTopics
}
}
})
I've simplified your code for the sake of ease, but see the below example on how to achieve this (if i've understood your question correctly):
new Vue({
el: "#app",
data() {
return {
selectedRoom: null,
rooms: [
{name: 'room 1', topicId: 1},
{name: 'room 2', topicId: 2},
{name: 'room 3', topicId: 3}
],
topics: [
{id: 1, name: 'topic 1', options: ['one', 'two', 'three']},
{id: 2, name: 'topic 2', options: ['four', 'five', 'six']},
{id: 3, name: 'topic 3', options: ['seven', 'eight', 'nine']}
],
selectedTopicOption: null,
}
},
computed:{
selectedRoomTopic() {
const selected = this.selectedRoom
return (selected)
? this.topics.find(x => x.id === selected.topicId)
: null
}
}
})
<div id="app">
<label>Select a room</label>
<select v-model="selectedRoom">
<option disabled selected>Rooms</option>
<option v-for="room in rooms" :value="room">
{{ room.name }}
</option>
</select>
<div v-if="selectedRoomTopic">
<label>Select a Topic</label>
<select v-model="selectedTopicOption">
<option disabled selected>Topics</option>
<option v-for="option in selectedRoomTopic.options" :value="option">
{{option}}
</option>
</select>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>

VueJS: Updating component collection data from its child

Given Todo list with filtering:
list.vue:
<script>
import TodoItem from './todo_item.vue';
export default {
components: { TodoItem },
props: ['selectePriority'],
data: {
items: [
{ name: 'Do shopping', priority: 'high' },
{ name: 'Play games', priority: 'low' }
]
},
computed: {
selectedItems: function() {
if(this.selectedPriority == 'all') {
return this.items;
} else {
var selectedPriority = this.selectedPriority;
return this.items.filter(function(item) {
return item.priority == selectedPriority
});
}
}
},
}
</script>
<template>
<div>
<select v-model="selectedPriority">
<option value="all">All</option>
<option value="low">Low</option>
<option value="high">High</option>
</select>
<todo-item
v-for="item in selectedItems"
:name="item.name"
:priority="item.priority"
/>
</div>
</template>
todo_item.vue:
<script>
export default {
props: ['name', 'priority']
}
</script>
<template>
<div>
<p>{{ name }}</p>
<select v-model="priority">
<option value="low">Low</option>
<option value="high">High</option>
</select>
</div>
</template>
html:
<list />
Now, when for example filter is set to all, I change Play games to priority high and change filter to high, I will see only Do shopping, as priority was not updated in items collection and it was re-rendered.
What is proper way to update collection data from child components in Vue.js?
computed properties have the ability to create and return a filtered list.
this example uses lodash
data: {
items: [
{name: 'thing 1', value: 1000},
{name: 'thing 2', value: 50},
{name: 'thing 3', value: 250},
{name: 'thing 4', value: 342},
],
},
computed: {
orderedItems() {
let items = []
return _.orderBy(this.items, 'value', 'desc');
},
}
to update pass the index from orderedItems array into the "this.items" array.
I found some solution that works - instead of passing all params of todo-item into component, pass whole object:
<todo-item
v-for="item in selectedItems"
:item="item"
/>
Then object in parent collection is updated automatically.
Is that a good way of doing that in Vue?

AngularJS disable dropdown option which previously selected

var demoApp = angular.module('myApp', []);
demoApp.controller('QaController', function($scope, $http) {
$scope.loopData = [{}, {}];
$scope.questions = {
model: null,
availableOptions: [
{id: '1', name: 'What is your childhood name?'},
{id: '2', name: "What is your first school?"},
{id: '3', name: "What is your first job place?"},
{id: '4', name: "What is your pet name?"}
]
};
$scope.submit = function() {
$scope.result = $scope.loopData;
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp">
<div class="wrapper wrapper-content middlealigen col-sm-12" ng-controller="QaController">
<form ng-submit="submit();">
<div ng-repeat="x in loopData">
<h5>Q. {{$index + 1}}</h5>
<select class="form-control" name="question-drop" id="question_dropdown" ng-model="x.question" ng-options="option.id as option.name for option in questions.availableOptions">
<option value="">Select Question</option>
</select>
<input type="text" placeholder="Enter Answer" name="answer" class="form-control" ng-model="x.answer" />
<div class="m-b"></div>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
<div ng-if="result">
<pre>{{result | json}}</pre>
</div>
</div>
</body>
Can you please check my code snippet. Here is two dropdown.
If I select What is your childhood name? from Q. 1 dropdown then this option should be disabled in the Q. 2 dropdown. How can I do that?
var demoApp = angular.module('myApp', []);
demoApp.controller('QaController', function($scope, $http) {
$scope.loopData = [];
$scope.loopData = [{
model: null,
question : "",
availableOptions: [
{id: '1', name: 'What is your childhood name?',disable : false},
{id: '2', name: "What is your first school?",disable : false},
{id: '3', name: "What is your first job place?",disable : false},
{id: '4', name: "What is your pet name?",disable : false}
]
},{
model: null,
question : "",
availableOptions: [
{id: '1', name: 'What is your childhood name?',disable : false},
{id: '2', name: "What is your first school?",disable : false},
{id: '3', name: "What is your first job place?",disable : false},
{id: '4', name: "What is your pet name?",disable : false}
]
}]
$scope.changItem = function(index,_id){
$scope.loopData = $scope.loopData.map(function(obj,i){
debugger
if(i > index){
obj.availableOptions.map(function(item){
if(item.id == _id ){
item.disable = true
}else{
item.disable = false
}
return item
})
}else{ debugger
obj.availableOptions.map(function(item){
debugger
if(item.id == _id ){
item.disable = true
}else{
item.disable = false
}
return item
})
}
return obj
});
}
$scope.submit = function() {
$scope.result = $scope.loopData;
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp">
<div class="wrapper wrapper-content middlealigen col-sm-12" ng-controller="QaController">
<form ng-submit="submit();">
<div ng-repeat="x in loopData track by $index">
<h5>Q. {{$index + 1}}</h5>{{x.modelVal}}
<select
ng-change="changItem($index,x.question)" ng-model="x.question" >
<option value="">Select Question</option>
<option ng-disabled="option.disable" ng-repeat="option in x.availableOptions" value="{{option.id}}">{{option.name}}</option>
</select>
<input type="text" placeholder="Enter Answer" name="answer" class="form-control" ng-model="x.answer" />
<div class="m-b"></div>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
<div ng-if="result">
<pre>{{result | json}}</pre>
</div>
</div>
</body>
You might create a custom filter to be more generic (for more select inputs).
The filter could be:
.filter('excludeEqualAnswers', function() {
return function(input, index, selectedQuestions) {
if (!selectedQuestions[index].question) {
function notExistInSelectedQuestions(output) {
return !selectedQuestions.map(val => val.question).includes(output.id);
}
return input.filter(notExistInSelectedQuestions);
} else {
return input
}
}
})
Then you can filter the options of your select input based upon your custom filter like this:
<select class="form-control" name="question-drop" id="question_dropdown" ng-model="x.question" ng-options="option.id as option.name for option in questions.availableOptions | excludeEqualAnswers:$index:loopData">
<option value="">Select Question</option>
</select>
Here's a working fiddle

data-ng-model and data-ng-change are not working with data-ng-selected

var appCompAssets = angular.module('app.company.assets', []);
appCompAssets.controller('locationDetailCTRL', function($scope, $http) {
// LOAD LOCATION DETAILS
$scope.loadBranches = function() {
$http.get('../getBranches_id_name/' + $scope.compid)
.then(
function(response) {
if (response.data.length !== 0) {
$scope.getBranches_id_name = response.data;
console.log($scope.getBranches_id_name);
}
},
function(response) {
// error handling routine
console.log('$Error: no data for branch id & name');
});
};
$scope.loadLocations = function(branch_id) {
$scope.branchid = branch_id;
$http.get('../getLocations_id_name/' + $scope.branchid)
.then(
function(response) {
if (response.data.length !== $scope.branchid) {
$scope.getLocations_id_name = response.data;
console.log($scope.getLocations_id_name);
}
},
function(response) {
// error handling routine
console.log('$Error: no data for location id & name');
});
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-ng-app="app.company.assets" data-ng-controller="locationDetailCTRL">
<div class="row" data-ng-init="loadBranches()">
<div class="col-sm-12">
<div class="form-group">
<label for="branch_id" class="small"><i>Branch</i>
</label>
<select class="form-control input-sm" data-ng-init="loadLocations(assetInfo.branch_id)" data-ng-change="loadLocations(assets.branch_id)" id="branch_id" name="branch_id" data-ng-model="assets.branch_id">
<option data-ng-selected="assetInfo.branch_name ===b.branch_name" data-ng-repeat="b in getBranches_id_name" value="{{b.id}}">{{b.branch_name}}</option>
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<label for="location_id" class="small"><i>Location</i>
</label>
<select class="form-control input-sm" id="location_id" name="location_id">
<option value=""></option>
<option data-ng-repeat="l in getLocations_id_name" value="{{l.id}}" data-ng-selected="l.location_name == assetInfo.location_name">{{l.location_name}}</option>
</select>
</div>
</div>
</div>
</div>
Guys, I am having problem with making data-ng-selected, data-ng-model and data-ng-change work at the same time.
if without the data-ng-model and data-ng-change
the data-ng-selected is working fine.
Excluded data-ng-model and data-ng-change and remain only data-ng-selected, the output is as below:
Although, it is able to display the value wanted, when changing the branch(dropdown), the location(s) for the respective branch won't change since there are no ng-change and ng-model exist.
However, if with all the above mentioned data-ng attribute together(data-ng-model,ng-change and ng-selected), it will not display properly as the branch is not selected which it supposed to be selected. The output is as below:
for changing the branch and the location will change, that part is working fine.
Your kind assistance will be appreciated. Thank you!.
The response result on the top is for branch and the one at the bottom is for location. Thank you.
try like this, hope it helps , let me know in case you are looking for something different.
Plunker : http://plnkr.co/edit/VE5ja2kkV9Xp7og1CkAl?p=preview
in script
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.branches = [
{ id: 1, name: 'Testing Branch 1'},
{ id: 2, name: 'Testing Branch 2'},
{ id: 3, name: 'Testing Branch 3'}
];
$scope.locations = [
{ id: 1, branchId: 1, name: 'Office Room 1'},
{ id: 2, branchId: 1, name: 'Office Room 2'},
{ id: 3, branchId: 2, name: 'Office Room 3'},
{ id: 4, branchId: 3, name: 'Office Room 4'}
];
$scope.loadLocations = function(branchId) {
console.log('Selected BranchId: ' + branchId);
};
// for selecting options on page load set the model for both the select
$scope.selectedBranchId = 2;
$scope.selectedLocationId = 3;
});
in view.
<body ng-controller="MainCtrl">
<h1>Cascading DropDownList</h1>
<hr />
<h4>Branch</h4>
<select ng-options="branch.id as branch.name for branch in branches"
ng-model="selectedBranchId"
ng-change="loadLocations(selectedBranchId)">
<option value="">Select Branch</option>
</select>
<h4>Location</h4>
<select ng-options="location.id as location.name for location in locations | filter: { branchId: selectedBranchId }"
ng-model="selectedLocationId"
ng-disabled="!selectedBranchId">
<option value="">Select Location</option>
</select>
</body>
What you need is a cascading dropdown list, well your html code seems complex to me for what you're trying to achieve.
You can simplify it as follows.
angular
.module("demo", [])
.controller("DefaultController", DefaultController);
function DefaultController() {
var vm = this;
vm.branches = [
{ id: 1, name: 'Testing Branch 1' },
{ id: 2, name: 'Testing Branch 2' },
{ id: 3, name: 'Testing Branch 3' }
];
vm.locations = [
{ id: 1, branchId: 1, name: 'Office Room 1' },
{ id: 2, branchId: 1, name: 'Office Room 2' },
{ id: 3, branchId: 2, name: 'Office Room 3' },
{ id: 4, branchId: 3, name: 'Office Room 4' }
];
vm.loadLocations = loadLocations;
// set data
getData();
function loadLocations(branchId) {
// load locations here when branch is changed.
// if locations are loaded only when a branch is selected
// then you can remove the filter in ng-options for Location
console.log('Selected BranchId: ' + branchId);
};
function getData() {
// get data via AJAX here and set the selected options in the view via data binding (ngModel)
var data = {
branch: {
id: 3,
name: 'Testing Branch 3'
},
location: {
id: 4,
branchId: 3,
name: 'Office Room 4'
}
};
vm.branch = data.branch.id;
vm.location = data.location.id;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="demo">
<div ng-controller="DefaultController as ctrl">
<h1>Cascading DropDownList</h1>
<hr />
<h4>Branch</h4>
<select ng-options="branch.id as branch.name for branch in ctrl.branches"
ng-model="ctrl.branch"
ng-change="ctrl.loadLocations(ctrl.branch)">
<option value="">Select Branch</option>
</select>
<h4>Location</h4>
<select ng-options="location.id as location.name for location in ctrl.locations | filter: { branchId: ctrl.branch }"
ng-model="ctrl.location"
ng-disabled="!ctrl.branch">
<option value="">Select Location</option>
</select>
</div>
</div>
<div class="row" data-ng-init="loadBranches()">
<div class="col-sm-12">
<div class="form-group">
<label for ="branch_id" class="small"><i>Branch</i></label>
<select class = "form-control input-sm"
data-ng-options="b.id as b.branch_name for b in getBranches_id_name" data-ng-init="branch_id = assetInfo.branch_id" data-ng-model="branch_id"
data-ng-change="loadLocations(branch_id)" id="branch_id"
name="branch_id"></select>
</div>
</div>
</div>
<div class="row" data-ng-init="loadLocations(branch_id)">
<div class="col-sm-12">
<div class="form-group">
<label for ="location_id" class="small"><i>Location</i></label>
<select class = "form-control input-sm"
data-ng-options="l.id as l.location_name for l in getLocations_id_name"
id="location_id" name="location_id" data-ng-init="location_id = assetInfo.location_id" data-ng-model="location_id" data-ng-disabled="!branch_id" ></select>
</div>
</div>
</div>
Hi #Deep and #abdul mateen mohammed, with the above code, it works as i wanted, however, there is a problem, i could not save the value to the database (the value of the selected option is not saved to the database).
But with the code below, i can save the value to the database but it won't work as i wanted which by default it will pre-load the branch and location when on load. The only changes i made is by adding the "track by" in the ng-option.
<div class="row" data-ng-init="loadBranches()">
<div class="col-sm-12">
<div class="form-group">
<label for ="branch_id" class="small"><i>Branch</i></label>
<select class = "form-control input-sm"
data-ng-options="b.id as b.branch_name for b in getBranches_id_name track by b.id" data-ng-init="branch_id = assetInfo.branch_id" data-ng-model="branch_id"
data-ng-change="loadLocations(branch_id)" id="branch_id"
name="branch_id"></select>
</div>
</div>
</div>
<div class="row" data-ng-init="loadLocations(branch_id)">
<div class="col-sm-12">
<div class="form-group">
<label for ="location_id" class="small"><i>Location</i></label>
<select class = "form-control input-sm"
data-ng-options="l.id as l.location_name for l in getLocations_id_name track by l.id"
id="location_id" name="location_id" data-ng-init="location_id = assetInfo.location_id" data-ng-model="location_id" data-ng-disabled="!branch_id" ></select>
</div>
</div>
</div>
Your kind assistance will be appreciated. Thank you.
#Deep, this is how i saved the data to database. Thank you.
IN THE CONTROLLER:
function update() {
$this->model->update($_POST);
}
IN THE MODEL:
function update($data) {
$assetid = $data['assetid'];
unset($data['assetid']); // remove #assetid element from the array #data
$this->db->update('assets', $data, "`id` = {$assetid}");
}

Angularjs Dropdown OnChange Selected Text and Value

I am new to AngularJS and trying to get Selected Text and Value from Dropdown. I followed a lot of tutorials with still unable to get there. SelectedValue and SelectedText are always undefined. Below is my 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 a 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 and Children -", disabled: true },
{ id: 9, name: "Appliances", disabled: false },
{ id: 10, name: "Inside", disabled: false },
{ id: 11, name: "Games and 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 one more thing, I have defined my first item as Select a category... then Why first item in Dropdown is always empty.
Below is my fiddle sample.
http://jsfiddle.net/Qgmz7/136/
That's because, your model itemSelected captures the current value of your select drop down which is nothing but the value attribute of your option element. You have
<option ng-repeat="category in categories" value="{{category.id}}">
in your code, so in the rendered version, you'll get
<option ng-repeat="category in categories" value="0">
but you're expecting itemSelected to be your category object and any attempt to query id or other property will return undefined.
You can use ng-options with group by with little bit of change to your data or you can use normal ng-repeat, get the selectedIndex and lookup the category object from your categories list using that index. Showcasing the first approach here.
HTML
<select name="category-group" id="categoryGroup"
ng-model="itemSelected" ng-change="onCategoryChange(itemSelected)"
ng-options="category.name group by category.group for category in categories">
</select>
Updated Data
$scope.categories = [
{ id: 0, name: "Select a 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, you can add a group property which can be used in group by.
Here' an updated Fiddle to illustrate the idea.
You should use ng-options to set object to your ng-model value on change of you select options.
Markup
<select name="category-group" id="categoryGroup" class="form-control"
ng-model="itemSelected" ng-change="onCategoryChange(itemSelected)"
ng-options="category.name for category in categories">
<option value="0">Select a category...</option>
</select>
Fiddle Here
Update
For persisting style you have to use ng-repeat there, in that case you will only have id binded to your ng-model and while retrieving whole object you need to filter your data.
$scope.onCategoryChange = function () {
var currentSelected = $filter('filter')($scope.categories, {id: $scope.itemSelected})[0]
$window.alert("Selected Value: " + currentSelected.id + "\nSelected Text: " + currentSelected.name);
};
Updated Fiddle
<div ng-app="SelectApp">
<div ng-controller="selectController">
<select ng-change='onCategoryChange()' ng-model="itemSelected" ng-options="category.name for category in categories">
<option value="">-- category --</option>
</select>
</div>
//http://jsbin.com/zajipe/edit?html,js,output
A little change in your onCategoryChange() should work:
$scope.onCategoryChange = function () {
$window.alert("Selected Value: " + $scope.categories[$scope.itemSelected - 1].id + "\nSelected Text: " + $scope.categories[$scope.itemSelected -1].name);
};
JSFiddle: http://jsfiddle.net/Qgmz7/144/
ngChange only returns the value of your selected option and that's why you don't get the whole data.
Here's a working solution without changing your markup logic.
Markup:
<select
name="category-group"
id="categoryGroup"
class="form-control"
ng-model="id"
ng-change="onCategoryChange(id)">
ngChange handler:
$scope.onCategoryChange = function (id) {
//get selected item data from categories
var selectedIndex = $scope.categories.map(function(obj) { return obj.id; }).indexOf( parseInt(id) );
var itemSelected = $scope.categories[selectedIndex];
$window.alert("Selected Value: " + itemSelected.id + "\nSelected Text: " + itemSelected.name);
};
Another solution (little bit dirty) would be to change only the value of your options into something like this:
<option .... value="{{category.id}}|{{category.name}}">
...and inside your actual ngChange handler, just split the value to get all the values as an array:
$scope.onCategoryChange = function (itemSelected) {
$scope.itemSelected = itemSelected.split('|'); //string value to array
$window.alert("Selected Value: " + $scope.itemSelected[0] + "\nSelected Text: " + $scope.itemSelected[1]);
};
Here very Simple and easy code What I did
<div ng-app="myApp" ng-controller="myCtrl">
Select Person:
<select ng-model="selectedData">
<option ng-repeat="person in persons" value={{person.age}}>
{{person.name}}
</option>
</select>
<div ng-bind="selectedData">AGE:</DIV>
<br>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl',myCtrlFn);
function myCtrlFn($scope) {
$scope.persons =[
{'name': 'Prabu','age': 20},
{'name': 'Ram','age': 24},
{'name': 'S','age': 14},
{'name': 'P','age': 15}
];
}
</script>

Categories

Resources