【问题标题】:ng-model is not updatingng-model 没有更新
【发布时间】:2016-04-27 10:06:50
【问题描述】:

我的角度 ng-options 指令不起作用。更改选项时,ng-model 不会更新。

角度 sn-ps

scope.searchoptions = [
    { name: "All", id: 1 },
        {
            name: "Devices",
            id: 2
        }, {
            name: "Sessions",
            id: 3
        }, { 
            name: "Alerts", 
            id: 4 
        },{
            name: "Files", 
            id: 5 
        }];
scope.currentSearch = scope.searchoptions[0]; // Intial object 

// Html 片段

<div class="form-group l-h m-a-0">
    <select class="form-control"
        ng-options="item.name for item in searchoptions track by item.id" 
        ng-model="currentSearch">
    </select>
</div>

给定的代码在选择选项时没有更新模型

请注意:在我的具体情况下,ng-init 对我来说失败了。问题是我正在使用的值在 ng-init 运行时尚不可用:我通过 ajax 调用获得了值,此时 ng-init 已经完成

【问题讨论】:

标签: javascript angularjs angular-directive angularjs-ng-options


【解决方案1】:

你需要为select.ng-init="currentSearch = searchoptions[0]"中的ng-model初始化值

var app = angular.module("mainApp",  []);

app.controller('mainCtrl', function($scope){
  $scope.searchoptions = [
            { name: "All", id: 1 },
            {
                name: "Devices",
                id: 2
            }, {
                name: "Sessions",
                id: 3
            }, { name: "Alerts", id: 4 },
            { name: "Files", id: 5 }
        ];
        //$scope.currentSearch = scope.searchoptions[0].name; // Intial object
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div  ng-app="mainApp" ng-controller="mainCtrl">
  <div class="form-group l-h m-a-0">
        <select ng-if="searchoptions" class="form-control" ng-init="currentSearch = searchoptions[0]" ng-options="item.name for item in searchoptions track by item.id" ng-model="currentSearch">
        </select>
    
    {{currentSearch}}
    </div>
</div>

【讨论】:

  • ng-init 在我的具体情况下对我来说失败了。问题是我正在使用的值在 ng-init 运行时尚不可用:我通过 ajax 调用获得了值,此时 ng-init 已经完成..@nisar @jimbrooism
  • 添加一个 ng-if="searchoptions" 外部容器@BinsonEldhose
  • @BinsonEldhose 已尝试 ng-if="searchoptions.length"
【解决方案2】:

您的代码中有一些小错误。请查看给定的代码并更新它。给定的代码工作正常。

角度 sn-ps

$scope.searchoptions = [
            { name: 'All', id: '1' },
            { name: 'Devices', id: '2'}, 
            { name: 'Sessions', id: '3'}, 
            { name: 'Alerts', id: '4' },
            { name: 'Files', id: '5' }
];
$scope.currentSearch = $scope.searchoptions[0];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-19
    • 2017-02-21
    • 2018-11-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多