AngularJS - select tag - getting attribute from option when selected

天大地大妈咪最大 提交于 2019-12-02 03:57:27

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!