2014-11-05 58 views
0

如何在option的中将“selected”属性置于device.type的值相等的位置。出于某种奇怪的原因,即使device.type具有其他某些值,也会显示第一个option。哪里是把代码放在指令中的最佳位置,linkcompilecontroller在匹配选项中放置'selected'属性(在指令中)

template.html

<div> 

    <select ng-model="device.type"> 
     <option value="value1">value1</option> 
     <option value="value2" selected>value2</option> 
     . 
     . 
     . 
     <option value="valueN">valueN</option> 
    </select> 
</div> 

指令

app.directive('details', function() { 
    return { 
     restrict : 'E', 
     scope : { 
      device: '=', 
      ... 
     }, 
     templateUrl : 'template.html', 
     link : function(scope, element, attrs) { 
      // put 'selected' on option element where device.type is equivalent to 
      // is it preferrable to put logic here? or in controller or compile 
     } 
    }; 
}); 

感谢您的输入。谢谢。

+0

更改为'ng-model =“device.type”' - 即移除“{{}}”。您需要传递范围属性本身,而不是表达式。 – 2014-11-05 10:30:50

+0

@NewDev我已经删除了{{}}。问题依然存在。 – menorah84 2014-11-05 11:03:03

+0

实际上你并不需要'selected'属性 - 只要将你的'device.type'设置为任何你想要设置的值即可。 – 2014-11-05 11:07:21

回答

0

您不需要创建指令来实现该目标。 只需填写您选择ng-options并使用track by <some field>。 然后,当您的选择模型更改时,它将选择与您在track by <some field>中选择的字段对应的正确选项。

类似的东西:

<select 
    ng-model="device" 
    ng-options="device as device.type for device in devices track by device.type"> 
</select> 

所以,当你把一个设备对象的选择的模式,它会选择具有device.type匹配模型的选项。

相关问题