简体   繁体   English

如何在Angularjs中设置具有不存在值的选择框的默认值

[英]How to set default value of select box with non-existed value in Angularjs

Maybe this can has duplicated or maybe there's a way to solve this, 也许这可能有重复或者可能有办法解决这个问题,

but I couldn't find any way to solve this. 但我找不到任何方法来解决这个问题。

So please don't be angry with my silly question and give me some information or way to solve this. 所以请不要生气我的愚蠢问题,并给我一些信息或方法来解决这个问题。

Please see this fiddle. 请看这个小提琴。

Set default value of select box 设置选择框的默认值

What I want is, when I get array from http call , 我想要的是,当我从http call获取数组时,

how to set default value of select box with the value which is not in array. 如何设置选择框的默认值,其值不在数组中。

I've used ng-init but it didn't work. 我用过ng-init但是ng-init

I know there are other ways to solve this like using <options> tag and put first value of option or 我知道还有其他方法可以解决这个问题,比如使用<options>标签并将第一个值选为或者

using selected but I want to use ng-options . 使用selected但我想使用ng-options

No matter what you give is a link, doc, or something, it'll be great help to me. 无论你给出什么是链接,文档或其他东西,它对我来说都会有很大的帮助。

I'll wait for your any comments or answers. 我会等你的任何评论或答案。 :) :)

First solution you can add one more option tag for default value 首先,您可以为默认值添加一个选项标签

Html Code Html代码

<div ng-app="MyApp">
    <div ng-controller="MyCtrl">
        <select ng-options="opt as opt for opt in testOpt"
                data-ng-model="resultOpt"
                data-ng-change="checkResultOpt(resultOpt)">
        <option value=''>Choose Category </option>
        </select>

    </div>
</div>

Controller Code 控制器代码

 var MyApp = angular.module('MyApp', [])
.controller('MyCtrl', ['$scope', function ($scope) {
    $scope.testOpt = [
        'ID',
        'Name',
        'Email',
        'Address'
    ];
    $scope.resultOpt = '';
}]);

Working code 工作代码

Second Solution : you just add one more item in your array list after get from http call 第二个解决方案:从http调用中获取后,您只需在数组列表中再添加一个项目

Html Code Html代码

<div ng-app="MyApp">
    <div ng-controller="MyCtrl">
        <select ng-options="opt as opt for opt in testOpt"
                data-ng-model="resultOpt"
                data-ng-change="checkResultOpt(resultOpt)">
        </select>

    </div>
</div>

Controller Code : 控制器代码:

var MyApp = angular.module('MyApp', [])
.controller('MyCtrl', ['$scope', function ($scope) {
    $scope.testOpt = [
        'ID',
        'Name',
        'Email',
        'Address'
    ];
    $scope.testOpt.splice(0, 0, 'Choose Category');
    $scope.resultOpt = 'Choose Category';
}]);

Working Code 工作守则

hope this will help you 希望这个能对您有所帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM