在Angularjs中使用ng-options时如何更新ng-model?

时间:2015-02-23 10:29:20

标签: javascript angularjs

当我选择一个选项时,我无法更新我的模型。

以下是我的观点:

<select data-ng-model="period" ng-options="item.value as item.text for item in periodOptions"></select>

在我的controller.js中,我有以下内容:

$scope.periodOptions = [
            { text: "This week", value: 'week' },
            { text:"This month", value: 'month '},
            { text:"This year",  value: 'year' }, 
            { text:"All times",  value: 'all-time '}
        ];

$scope.Search = function () {

            return $http({
                url: '/api/get',
                method: 'GET',
                params: {
                    period: $scope.period
                }
            }).then(function(response) {
                console.log(response);
            }, function(reason) {
                alert(reason);
            });
        };

$ scope.period不会获取从User中选择的选项的值。我花了很多时间在这上面,并且无法弄清楚为什么会发生这种情况。

4 个答案:

答案 0 :(得分:6)

在我的情况下,ng-model未更新,因为我的select位于具有ng-if的元素中。

<div class="editor-panel" ng-if="editorEnabled">
    ...
    <select ng-options="item as item.description for item in items" ng-model="selectedItem"/>
    ...
</div>

ng-if创建另一个范围,ng-model引用此子范围中的变量而不是预期的变量。

要解决此问题,我将ng-model="selectedItem"值更改为ng-model="$parent.selectedItem

答案 1 :(得分:2)

以下是一个应该有效的解决方案(请注意,对现有代码使用ng-options="item as item.text ...而不是ng-options="item.value as item.text进行细微更改)。希望这有帮助!

&#13;
&#13;
var myCtrl = function($scope){
  
  $scope.periodOptions = [
            { text: "This week", value: 'week' },
            { text:"This month", value: 'month '},
            { text:"This year",  value: 'year' }, 
            { text:"All times",  value: 'all-time '}
        ];
  
$scope.Search = function () {
alert('will call api with period: '+$scope.period.text);
  /*
            return $http({
                url: '/api/get',
                method: 'GET',
                params: {
                    period: $scope.period
                }
            }).then(function(response) {
                console.log(response);
            }, function(reason) {
                alert(reason);
            });
            */
        };
  
  }
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app ng-controller="myCtrl">
<select data-ng-model="period" ng-options="item as item.text for item in periodOptions" ng-change="updatePeriod()"></select>
  <div>{{period}} </div>
  <button ng-click='Search()' >Search</button>
  </div>
&#13;
&#13;
&#13;

答案 2 :(得分:1)

试试这个

<div ng-controller="MyCtrl">
    <select data-ng-model="period" ng-options="item.value as item.text for item in periodOptions"></select>
    <span>period value=, {{period}}!</span>
</div>

答案 3 :(得分:0)

select和ngOptions的代码是正确的。但是我假设您希望在每次选项更改时调用$scope.Search函数。在这种情况下,您需要设置ngChange处理程序:

<select ng-model="period" 
        ng-options="item.value as item.text for item in periodOptions"
        ng-change="Search()">
</select>