2017-01-22 76 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 :) –