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 element I have. It is only demonstrative, value attribute should be send in the form.
<input ng-model="refreshedByExample" type="text">
<select ng-model="example">
<option value="1" data-something="valueForRefreshedByExample1">1</option>
<option value="2" data-something="valueForRefreshedByExample2">2</option>
<option value="3" data-something="valueForRefreshedByExample3">3</option>
</select>
Any ideas?
Thanks a lot everyone
Updating the answer with correct code
<input ng-model="refreshedByExample" type="text">
<select ng-model="example" ng-change="refreshByExample=example">
<option ng-value="valueForRefreshedByExample1">1</option>
<option ng-value="valueForRefreshedByExample2">2</option>
<option ng-value="valueForRefreshedByExample3">3</option>
</select>
See ng-value.
Also consider using ng-options if your values are contained in a array.
Please see below code, I think it maybe what you're looking for. A custom attribute type directive.
function exampleController($scope) {
}
function extractValue() {
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);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div class="container" ng-app="app">
<div class="row" ng-controller="exampleController">
<input ng-model="example" type="text">
<select ng-model="example">
<option value="1" data-something="valueForRefreshedByExample1" extract-value>1</option>
<option value="2" data-something="valueForRefreshedByExample2" extract-value>2</option>
<option value="3" data-something="valueForRefreshedByExample3" extract-value>3</option>
</select>
</div>
</div>
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
):
<input ng-model="example2" type="text">
<select ng-model="example2">
<option value="valueForRefreshedByExample1">1</option>
<option value="valueForRefreshedByExample2">2</option>
<option value="valueForRefreshedByExample3">3</option>
</select>
The exemples can be seen here https://plnkr.co/edit/gfYak9zkKsAu0I5eQHx0?p=preview
来源:https://stackoverflow.com/questions/40699857/angularjs-select-tag-getting-attribute-from-option-when-selected