2017-01-22 129 views
0

我的下拉框默认为“无偏好”,这是我想要的,但当它们加载到页面时,它会一直被其他选项覆盖。我如何保持“无偏好”作为默认值。正在覆盖的角度默认选择选项

接触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

添加

$scope.contact.teammate = ''; 

刚下:

$scope.contacts = doc.data; 

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

您还需要定义:

$scope.contact = {}; 

这样做只是下:

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

这里有一个Plunker例如:https://plnkr.co/edit/4hCSXURbc754IAHU3VyN?p=preview

我用超时模拟AJAX延迟。

+0

我添加了$ scope.contact =''; $ scope.contact.teammate ='';但“无偏好”在加载时仍会变为其中一个名称。 – yellavon

+0

这是因为$ scope.contact没有定义,因此contact.teammate正在尝试为未定义的属性队友设置一个值,并且它不起作用。我更新了我的答案:) –

+0

不客气。很高兴我能帮助和欢迎使用Javascript :) –