使用ng-options和AngularJS自动选择新增值

时间:2014-11-29 21:09:31

标签: javascript angularjs ng-options

我有一个如下所示的选择列表:

<select 
  class="form-control" 
  ng-model="locationList" 
  ng-options="location.place group by location.type for location in locationlist | orderBy:['type']" 
  ng-change="addMissingLocation(locationList)">

    <option value="">From</option>
</select>

ng-options列表的最后一项称为&#34;添加位置&#34;,并通过ng-change触发以下功能:

$scope.addMissingLocation = function (locationList) {
    if (locationList.place == "Add location") {
        $('.addMissingLocation').modal('show');
    }
}

模式显示,它允许用户使用以下函数添加新位置:

$scope.addLocationOtherExtra = function () {
    $scope.locationlist.push({ place: $scope.formLocationOther, type: "-Secondary Locations", main:false});
    jsonToLocationLocalStorage($scope.locationlist);
    $scope.formLocationOther = '';
    $('.addMissingLocation').modal('hide');
};

我想要完成的是,一旦用户引入新位置并且模态关闭,选择中的选定值就是这个新添加的值

我甚至不确定这样的事情是否可行。

任何提示?

1 个答案:

答案 0 :(得分:3)

添加新选项后,您应该将ngModel指向添加的选项。尝试此选择最后一个选项(新选项):

$scope.addLocationOtherExtra = function () {

    $scope.locationlist.push({ place: $scope.formLocationOther, type: "-Secondary Locations", main:false});
    $scope.locationList = $scope.locationlist[$scope.locationlist.length - 1];

    jsonToLocationLocalStorage($scope.locationlist);
    $scope.formLocationOther = '';
    $('.addMissingLocation').modal('hide');
};