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

Bes*_*esa 2 javascript angularjs

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

这是我的观点:

<select data-ng-model="period" ng-options="item.value as item.text for item in periodOptions"></select>
Run Code Online (Sandbox Code Playgroud)

在我的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);
            });
        };
Run Code Online (Sandbox Code Playgroud)

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

小智 7

在我的情况下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>
Run Code Online (Sandbox Code Playgroud)

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

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

  • 你救了我的命。 (2认同)