AngularJS在传递给控制器​​之前更改模型值

时间:2014-06-18 05:41:58

标签: angularjs controller coffeescript

我需要在将值传递给控制器​​之前更改模型值。这是我的代码:

<div class="col-sm-8" ng-controller="MeasureCtrl as mc">
    <select class="form-control" ng-model="measure" required="" 
           ng-options="m.name as m.name for m in mc.measures">
    </select>

</div>

它的工作原理如下:

enter image description here

为了显示我需要提供的选择框的默认值(最后一个值)

  

NG-模型=&#34;测量&#34;和ng-options =&#34; m.name作为m的m.name,mc.measures&#34;

你知道如果measure等于m.name,那么它会在选择框中显示measure(kg)。 问题是,当我将数据传递给控制器​​时,它会发送&#34; kg&#34;不是它的id(例如15)。 在那之后,我想到了另一个想法,这是我的方法:

<div class="col-sm-8" ng-controller="MeasureCtrl as mc">
    <select class="form-control" ng-init="measureId = mc.getMeasureIdByName(measure)" ng-model="measure" required="" name="mc.getMeasureIdByName(measure)"
            ng-options="m.name as m.name for m in mc.measures">
    </select>
    <input type="hidden" ng-model="measureId" name="measureId"/>
    {{measureId}}
</div>

我有一个关于如何发送measureId而不是测量的ID?

1 个答案:

答案 0 :(得分:0)

您需要在表达式中选择ID:

ng-options="m.name as m.name for m in mc.measures"

成为:

ng-options="m.id as m.name for m in mc.measures"

从文档中,您需要使用[select value] as [label to show] for [item from array] in [array]