【问题标题】:Model isn't updating when selected option changes所选选项更改时模型未更新
【发布时间】:2016-03-08 23:22:48
【问题描述】:

我的 Angular.js 项目具有一个绑定到模型的选择元素。加载时选择了适当的选项,但是选择另一个选项似乎不会更新模型,至少不会永久更新。如果我以编程方式更改模型,但结果符合预期。

控制器:

angular.module('myApp.controllers').controller('HomeCtrl',function($scope){
  $scope.month = "08"; // this default value is selected on-load as expected
  $scope.updateMonth = function() {
   console.log($scope.month); // this shows the original value not the newly selected value
   // a http request and other things happen here...
  };
  $scope.logMonth = function(month) {
   console.log(month); // this shows the newly selected value as expected
  }
 });

模板:

<select ng-model="month" ng-change="logMonth(month);">
 <option value="07">07</option>
 <option value="08">08</option>
 <option value="09">09</option>
</select>
<button ng-click="updateMonth();">Update Month</button>

【问题讨论】:

  • 在您的模板中,logMonth(month); 存在,但您在 $scope.logMonth 中没有该参数...当您仅使用 ng-change="logMonth()" 时会发生什么?
  • 控制台出现错误?
  • 刚刚创建了一个jsFiddle,我无法复制您的问题。
  • 代码中多余的});是复制粘贴的吗?
  • ZackMacomber 和 Akis_Tfs 道歉,看起来我在编辑一些代码以使大家更容易阅读时错过了一些东西,我刚刚更新了它。 Lex 感谢您的测试,这可能表明这是周围代码的问题。

标签: javascript angularjs angularjs-scope angularjs-ng-model


【解决方案1】:

听起来像是一个角度范围问题。范围继承适用于范围上的对象,但不适用于原语。尝试将$scope.month = "08" 更改为$scope.month = {selected: "08"}。然后在您的控制器中,将 html 更改为以下内容。

&lt;select ng-model="month.selected" ng-change="logMonth(month.selected);"&gt;

【讨论】:

  • 这成功了。我的文本输入和其他表单元素正在使用 $rootScope 并且它们的行为符合预期,所以我认为 $scope 也会。由于我对 Angular.js 比较陌生,因此我将不得不对具体细节进行更多阅读。再次感谢!
猜你喜欢
  • 1970-01-01
  • 2017-05-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-24
  • 1970-01-01
  • 1970-01-01
  • 2018-10-29
  • 1970-01-01
相关资源
最近更新 更多