Angularjs - Select Tag - Getting Attribute From Option When Selected
So I have a select tag that shows some options and I wish that when an option is selected it takes the data-something attribute and pastes its value (of the attribute) in the input
Solution 1:
Updating the answer with correct code
<inputng-model="refreshedByExample"type="text"><selectng-model="example"ng-change="refreshByExample=example"><optionng-value="valueForRefreshedByExample1">1</option><optionng-value="valueForRefreshedByExample2">2</option><optionng-value="valueForRefreshedByExample3">3</option></select>
See ng-value.
Also consider using ng-options if your values are contained in a array.
Solution 2:
Please see below code, I think it maybe what you're looking for. A custom attribute type directive.
functionexampleController($scope) {
}
functionextractValue() {
return {
restrict: 'A',
scope: false,
link: function($scope, $element, $attr) {
if ($attr.something) {
$element[0].value = $attr.something;
}
}
};
}
angular
.module('app', [])
.controller('exampleController', exampleController)
.directive('extractValue', extractValue);
<scriptsrc="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script><divclass="container"ng-app="app"><divclass="row"ng-controller="exampleController"><inputng-model="example"type="text"><selectng-model="example"><optionvalue="1"data-something="valueForRefreshedByExample1"extract-value>1</option><optionvalue="2"data-something="valueForRefreshedByExample2"extract-value>2</option><optionvalue="3"data-something="valueForRefreshedByExample3"extract-value>3</option></select></div></div>
Solution 3:
I prefer use ng-options
in these situations.
<select ng-model="example"
ng-options="item.value as item.id for item in array">
</select>
And the array like
$scope.array = [
{id: 1, value: 'valueForRefreshedByExample1'},
{id: 2, value: 'valueForRefreshedByExample2'},
{id: 3, value: 'valueForRefreshedByExample3'}
];
EDIT:
The example with Value (if valueForRefreshedByExample1
isn't a string, use ngValue
):
<inputng-model="example2"type="text"><selectng-model="example2"><optionvalue="valueForRefreshedByExample1">1</option><optionvalue="valueForRefreshedByExample2">2</option><optionvalue="valueForRefreshedByExample3">3</option></select>
The exemples can be seen here https://plnkr.co/edit/gfYak9zkKsAu0I5eQHx0?p=preview
Post a Comment for "Angularjs - Select Tag - Getting Attribute From Option When Selected"