AngularJS如何将data-image属性添加到选项中

问题描述 投票:1回答:2

我想将自定义数据属性添加到选项标记。

例如:

<select>
    <option data-image="url 1">Val 1</option>
    <option data-image="url 2">Val 2</option>
    <option data-image=" ... "> ... </option>
    <option data-image="url N">Val N</option>
<select>

我怎样才能做到这一点?

angularjs ng-options
2个回答
2
投票

使用select指令是不可能的(参见documentation)。但你可以用ngRepeatsee the documentation)轻松制作你想要的东西:

<select ng-model="choice">
    <option ng-repeat="item in itemsList" data-image="{{item.url}}">{{item.label}}</option>
</select>

JSFiddle


0
投票

对@ Blackhole的回答做了一点修改。试试这个代码笔:

CODEPEN

function loadCountryFlagCtrl($scope) {

   $scope.countries = [
    {
      country_id: "SL", 
      name:"Sri Lanka",      flag:"http://icons.iconarchive.com/icons/gosquared/flag/24/Sri-Lanka-flat-icon.png"
    },{
      country_id: "IND", 
      name:"India",      flag:"http://icons.iconarchive.com/icons/gosquared/flag/24/Andorra-flat-icon.png"
    }
  ];

}

和HTML:

<div ng-controller="loadCountryFlagCtrl">
      <div class="content">
        <div class="header">
          <form action="">


             <div class="select_list" ng-class='{active:active}' ng-click="active=!active">
    <span ng-style="{'background-image':'url('+countries.country_selected.flag+')'}">{{countries.country_selected.name}}</span>
    <ul class="options">
        <li class="select_list_option" ng-repeat="country in countries" ng-click="countries.country_selected=country" ng-style="{'background-image':'url('+country.flag+')'}">{{country.name}}</li>
        </ul>
</div>
          <br/>
             <div>selected country:{{countries.country_selected.name}}</div>
           </form>


        </div>

    </div>

和CSS:

.select_list{
    background-color: #fff;
    border: 1px solid #b3b3b3;
    cursor: pointer;
    height: 21px;
    line-height: 21px;
    padding: 3px 5px;
    position: relative;
    vertical-align: middle;
    width: 250px;
}
.select_list:after{
    content:"▼";
    position:absolute;
    right:3px;
    color:#b3b3b3;
}
.select_list > .options{
    display:none;
    position:absolute;
    top:100%;
    left:-1px;
    width:100%;
    border:1px solid #666;
    padding:0;
    margin:0;
}

.select_list.active > .options{
    display:block;
}

.select_list > span, .select_list > .options li {
    background-position: 5px center;
    background-repeat: no-repeat;
    padding-left: 30px;
    list-style:none;
}

.select_list > .options li:hover {
    background-color:#eee;
}

希望这对其他程序员有帮助:)

© www.soinside.com 2019 - 2024. All rights reserved.