如何在Angular中选择选项时触发表达式

时间:2016-01-12 13:33:36

标签: javascript html angularjs

我将以下代码包装在ng-repeat

<select class="selectpicker input input-halfwide">
     <option disabled selected> -- Select your destination -- </option>
     <option ng-repeat="(key, country) in home.List" value="key" ng-model="home.status.selectedOption">{{country.title}}
     </option>
</select>

我希望当用户选择一个选项时,在控制器中执行表达式home.doSomething()。

如何实现这一目标?

2 个答案:

答案 0 :(得分:2)

您可以使用选择中的ng-change执行此操作:

<select class="selectpicker input input-halfwide"
        ng-model="home.status.selectedOption"
        ng-change="home.doSomething()">
    <option disabled selected> -- Select your destination -- </option>
    <option ng-repeat="(key, country) in home.List" value="{{ key }}"
            ng-selected="{{ key == home.status.selectedOption }}">
        {{country.title}}
    </option>
</select>

另请注意,我已将ng-model指令移至select而非option元素。

更好的做法是使用ng-options指令:

<select class="selectpicker input input-halfwide"
        ng-model="home.status.selectedOption"
        ng-change="home.doSomething()"
        ng-options="country.id as country.name for country in home.List">
    <option disabled selected> -- Select your destination -- </option>
</select>

答案 1 :(得分:0)

您需要使用ng-change来检测选择更改,并使用ng-model上所选值的select

<select class="selectpicker input input-halfwide" ng-change="home.doSomething()" ng-model="home.status.selectedOption">
   <option disabled selected> -- Select your destination -- </option>
   <option ng-repeat="(key, country) in home.List" value="key">{{country.title}}</option>
</select>

现在,您可以在控制器中使用$scope

直接使用所选值
$scope.home.doSomething = function () {
    // $scope.home.status.selectedOption
};