2016-05-16 105 views
0

我正在使用ng選項來爲我的選擇標籤選擇用戶。一切正常,但首次選擇一個選項後,默認空白值消失。如果我想再次恢復到默認值,該怎麼辦?如何做到這一點?我怎樣才能保留這個空白值?AngularJS ng-options在選擇選項後刪除了默認空白值

這裏是我的代碼示例:

<!DOCTYPE html> 
<html ng-app="app"> 

    <head> 
    <link rel="stylesheet" href="style.css"> 
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> 
    </head> 

    <body ng-controller="myController"> 
    <h1>Hello World!</h1> 
    <select ng-model="mySelection" name="" id="" ng-options="x.value as x.label for x in myOptions"> 

    </select> 
    </body> 

</html> 

<script> 
    var app = angular.module('app', []); 
    app.controller('myController', function($scope){ 
    $scope.myOptions = [{ 
     "value": null, 
     "label": null, 
    },{ 
     "value": "First", 
     "label": "First", 
    },{ 
     "value": "Second", 
     "label": "Second", 
    },{ 
     "value": "Third", 
     "label": "Third", 
    }] 
    }); 
</script> 

這裏是plunker:http://plnkr.co/edit/5f17YxRfWFI4g40t3NEf?p=preview

+0

嗨,當獲得值null調用函數 –

+0

什麼函數?你能演示一個代碼嗎? –

回答

2

使用

<select ng-model="mySelection" name="" id="" ng-options="x.value as x.label for x in myOptions"> 
    <option value=""></option> 
    </select> 

不要用僞空對象污染你的 'myOptions',因爲API不會返回相同的結果。您需要在表示層處理它,如上所示。同時節約,如使用選擇空的,它將被保存爲空(如果處理不當)

,你也可以有這樣的事情

<option value="">---select---</option> 
+0

哇!謝謝!從來不知道這個詭計:) –

+0

歡迎。如果你滿意,你能接受答案嗎:) – CodingNinja

1

只是空白選項添加到您的選項,並選擇默認空白像:

<!DOCTYPE html> 
<html ng-app="app"> 

    <head> 
    <link rel="stylesheet" href="style.css"> 
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> 
    </head> 

    <body ng-controller="myController"> 
    <h1>Hello World!</h1> 
    <select ng-model="mySelection" name="" id="" ng-options="x.value as x.label for x in myOptions"> 

    </select> 
    </body> 

</html> 

<script> 
    var app = angular.module('app', []); 
    app.controller('myController', function($scope){ 
    $scope.mySelection = ''; 
    $scope.myOptions = [{ 
     "value": "", 
     "label": "", 
    },{ 
     "value": "First", 
     "label": "First", 
    },{ 
     "value": "Second", 
     "label": "Second", 
    },{ 
     "value": "Third", 
     "label": "Third", 
    }] 
    }); 
</script> 

這裏我們添加空白選項

{ 
    "value": "", 
    "label": "", 
} 

,並選擇THA t空選項$scope.mySelection = '';

相關問題