正在覆盖Angular默认选择选项

时间:2017-01-22 00:19:52

标签: angularjs

我的下拉框默认为"无偏好"这就是我想要的,但是当它们加载到页面中时,它会被其他选项覆盖。我如何保持"没有偏好"作为默认值。

接触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);
        });
    });

1 个答案:

答案 0 :(得分:1)

添加

$scope.contact.teammate = '';

就在下面:

$scope.contacts = doc.data;

这将默认为没有值''的选项,或者如果你想默认为其他东西,只需将值设置为它。

您还需要定义:

$scope.contact = {};

在下面做:

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

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

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

相关问题