选择值更改时,角度模型值不会更新

时间:2016-06-02 04:07:55

标签: javascript angularjs ionic-framework

我的控制器中有以下代码

$scope.currencies = [
    { "currency_code": "USD", "currency_name": "American Dollar" },
    { "currency_code": "AUD", "currency_name": "Australian Dollar" }, 
    { "currency_code": "BRL", "currency_name": "Brazilian Real" }, 
    { "currency_code": "CAD", "currency_name": "Canadian Dollar" }, 
    { "currency_code": "CHF", "currency_name": "Swiss Franc" }, 
    { "currency_code": "CLP", "currency_name": "Chilean Peso" }
]

$scope.selectedCurrency = "USD";

$scope.doStuffs = function(){
   alert($scope.selectedCurrency);
}

在我的视图中

<div class="selected_currency">{{selectedCurrency}}</div>
<select id="currency" name="currency" ng-model="selectedCurrency" 
ng-options="currency.currency_code as currency.currency_code for currency in currencies"> 
</select>

问题

当我从select更改货币并执行doStuffs()功能时,它会提醒默认值USD,模型selectedCurrency未采用更改后的值。

然而,表达式{{selectedCurrency}}效果很好。

有人可以告诉我如何在选择值更改时更新模型吗?

由于

更新

这不起作用

<ion-view view-title="My Stuffs" ng-controller="MyCtrl">
    <ion-content> 
           <!-- other tags -->
    </ion-content>
</ion-view>

但是,以下代码有效(我刚在ng-controller标签中定义了ion-content指令)

<ion-view view-title="My Stuffs">
        <ion-content  ng-controller="MyCtrl"> 
               <!-- other tags -->
        </ion-content>
    </ion-view>

3 个答案:

答案 0 :(得分:0)

只需在选择元素

中添加ng-change="doStuffs()"即可
<select 
   id="currency" 
   name="currency" 
   ng-model="selectedCurrency" 
   ng-change="doStuffs()"
   ng-options="currency.currency_code as currency.currency_code 
   for currency in currencies"> 
</select>

请在这里演示 https://plnkr.co/edit/1gueFbhKkRrqmRiSoTYB?p=preview

答案 1 :(得分:0)

要在控制器内更新或更改值,您需要在其上编写ng-change功能

<select id="currency" name="currency" ng-model="selectedCurrency" ng-change="doStuffs()" ng-options="currency.currency_code as currency.currency_code 
   for currency in currencies">
</select>

代码

$scope.doStuffs = function(){
console.log($scope.selectedCurrency);}

答案 2 :(得分:0)

当通过引用更新值时,双向绑定在角度中起作用。在您的示例中,模型string是javascript中的原始$scope.model.selectedCurrency = 'USD'; ,并且永远不会通过引用进行更新,并且值更改将不会以双向方式工作。

为了使其工作,将模型绑定到object的属性:

<强>控制器

ng-model="model.selectedCurrency" 

<强> HTML

$text = 'Dear [NAME],
<br /><br />
Someone (hopefully you) requested a password reset at [SITE_URL].
<br /><br />
To reset your password, please follow the following link: [EMAIL_LINK]';

preg_match_all('/\[([A-Z_]+)\]/', $text, $matches);