使用ng-model with select来显示数据属性而不是值?

时间:2015-06-03 01:51:17

标签: javascript html angularjs angular-ngmodel

我目前有一个简单的选择列表,其中包含数据属性和值:

<select ng-model="myList">
    <option value="1" data-name="Test name 1">Option 1</option>
    <option value="2" data-name="Test name 2">Option 2</option>
    <option value="3" data-name="Test name 3">Option 3</option>
</select>

<div id="displaySelected">
    {{myList}}
</div>

在我的div中(ID为displaySelected),它当前显示所选选项的value

如何更改此设置以显示data-name属性?

1 个答案:

答案 0 :(得分:1)

我不确定问题中未提及的完整数据结构和其他可能性。但这是一个简单的静态列表解决方案。

app.directive('dataselector', function(){
 return{
    restrict:'A',
    require:['ngModel','select'], //Require ng-model and select in order to restrict this to be used with anything else
    link:function(scope, elm, attrs, ctrl){
      //get configured data to be selected, made this configurable in order to be able to use it with any other data attribs
      var dataProp = attrs.dataselector,
          ngModel = ctrl[0]; 

      elm.on('change', handleChange);//Register change listener

      scope.$on('$destroy', function(){
        elm.off('change', handleChange);
      });

      function handleChange(){
        //get the value
        var value = this.value;
        //get the dataset value
        var dataVal = elm[0].querySelector('option[value="' + this.value + '"]').dataset[dataProp];
        //reset ngmodel view value
        ngModel.$setViewValue(dataVal);
        ngModel.$render();
        //set element value so that it selects appropriate item
        elm.val(value);
      }
    }
  }
});

并将其用作:

 <select ng-model="myList" dataselector="name">

注意:如果您使用不同的方式(您没有向我们展示),则根据数据属性中填充值的数据结构构建选择选项(如{ {1}}),您可以使用ng-repeat注册更改事件,并且可以在处理程序中使用数据值设置另一个属性并使用它。

ng-change="selectedItem(itemFromRepeat)"
var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {

}).directive('dataselector', function() {

  return {
    restrict: 'A',
    require: ['ngModel', 'select'],
    link: function(scope, elm, attrs, ctrl) {
      var dataProp = attrs.dataselector;
      elm.on('change', handleChange);

      scope.$on('$destroy', function() {
        elm.off('change', handleChange);
      });

      function handleChange() {
        var value = this.value;
        var dataVal = elm[0].querySelector('option[value="' + this.value + '"]').dataset[dataProp];
        ctrl[0].$setViewValue(dataVal);
        ctrl[0].$render();
        elm.val(value);
      }
    }
  }

});