Javascript 为什么 ng-model 不更新控制器值选择?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32038202/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 07:33:02  来源:igfitidea点击:

Why ng-model does not update controller value select?

javascripthtmlangularjsng-optionsangularjs-ng-model

提问by alvarezsh

This is the code HTML:

这是代码 HTML:

<div ng-controller="SelectCtrl">
    <p>selected item is : {{selectedItem}}</p>
    <p> age of selected item is : {{selectedItem.age}} </p>
    <select ng-model="selectedItem" ng-options="item.name for item in items">
    </select>
</div>

This is the code AngularJS:

这是 AngularJS 的代码:

var app = angular.module('myApp', []);

app.controller('SelectCtrl', function($scope) {
    $scope.items = [{name: 'one', age: 30 },{ name: 'two', age: 27 },{ name: 'three', age: 50 }];
    $scope.selectedItem = $scope.items[0];
    console.log($scope.selectedItem); //it's not update :(
});

in the view the new value updated every time I change the select, but the controller does not update the current value of the select. What should I do?

在视图中每次更改选择时都会更新新值,但控制器不会更新选择的当前值。我该怎么办?

Thanks!

谢谢!

回答by Pankaj Parkar

To get updated or change value inside your controller, you could write ng-changefunction on it. Then you could check the updated value inside controller.

要更新或更改控制器内的值,您可以ng-change在其上编写函数。然后你可以检查控制器内部的更新值。

Markup

标记

<select ng-model="selectedItem" ng-options="item.name for item in items"
  ng-change="changeSelectedItem()">
</select>

Code

代码

$scope.changeSelectedItem = function(){
   console.log($scope.selectedItem);
}

Other way could be you could simply use {{selectedItem}}on html somewhere. That will also give an idea about how selectedItemvalue is updating.

其他方式可能是您可以简单地{{selectedItem}}在某处使用html。这也将提供有关selectedItem价值如何更新的想法。

回答by Sajeetharan

Because you are always taking the first item of the array in the controller,

因为你总是在控制器中取数组的第一项,

$scope.selectedItem = $scope.items[0];
console.log($scope.selectedItem);

Just change your JS like this,

像这样改变你的JS,

$scope.changeSelectedItem = function(){
   console.log($scope.selectedItem);
}

And the View use the ng-change to get the selected item

并且视图使用 ng-change 来获取所选项目

<select ng-model="selectedItem" ng-options="item.name for item in items"
  ng-change="changeSelectedItem()">
</select>