繁体   English   中英

Angular默认选择选项被覆盖

[英]Angular default select option being overwritten

我的下拉框默认为“无首选项”,这是我想要的,但是当其他选项加载到页面中时,它总是被其他选项覆盖。 如何保持“无首选项”为默认设置。

contact-form.html:

<p>
  <label>Preference</label> 
  <select id="name" class="form-control" ng-init="" ng-model="contact.teammate" ng-options='contact.id as (contact.firstName + " " + contact.lastName) for contact in contacts'>
        <option value="">No Preference</option>
  </select>
</p>

app.js:

var app = angular.module("contactsApp", ['ngRoute'])
    .config(function($routeProvider) {
        $routeProvider
            .when("/new/contact", {
                controller: "NewContactController",
                templateUrl: "contact-form.html",
                  resolve: {
                    contacts: function(Contacts) {
                        return Contacts.getContacts();                   
                    }
                  }

            })
            .otherwise({
                redirectTo: "/"
            })
    })
    .service("Contacts", function($http) {
        this.getContacts = function() {
            return $http.get("/contacts").
                then(function(response) {
                    return response;
                }, function(response) {
                    alert("Error finding contacts.");
                });
        }
    })
    .controller("NewContactController", function($scope, $location, Contacts) {  
        console.log("Entered new contacts controller");
    Contacts.getContacts().then(function(doc) {
            $scope.contacts = doc.data;
        }, function(response) {
            alert(response);
        });
    });

$scope.contact.teammate = '';

在下面:

$scope.contacts = doc.data;

这会将其默认为不带值''的选项,或者如果您想默认为其他值,则只需为其设置值即可。

您还需要定义:

$scope.contact = {};

只是在下面做:

console.log("Entered new contacts controller");

这是一个Plunker示例: https ://plnkr.co/edit/4hCSXURbc754IAHU3VyN ? p = preview

我使用超时来模拟ajax延迟。

暂无
暂无

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

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