2017-07-01 29 views
0

我是angular js的新手。在我的代碼中,用戶更改單選按鈕的值。並根據所選擇的單選按鈕的值,一段代碼被從NG-開關加載
HTML:在使用ng-model的select中刪除空選項

<body ng-app=""> 
    <div ng-repeat="button in modes"> 
    <label> 
     <input type="radio" ng-model="data.mode" value="{{button.value}}" ng-click="clearObjectIdModal()" name="e_modes"> 
     {button.label}} 
    </label> 
    </div> 

    <div ng-switch on="data.mode"> 

    <div ng-switch-when="client"> 
     <label for="e_selected_object_item_id">Select Client name: </label> 
     <select id="e_selected_object_item_id" name="e_selected_object_item_id" ng-model="currentDataItem.object_id" required> 
     <option ng-repeat="item in customersListArr" value="{{ item.id }}">{{ item.Name }}</option> 
     </select> 
    </div> 

    <div ng-switch-when="agent"> 
    // This part is similar to the previous one 
    </div> 

    </div> 
</body> 

控制器部分:

$scope.data = {}; 
$scope.setFile = function() { 
    if ($scope.data.mode == 'client') 
    return 'client'; 
    else if ($scope.data.mode == 'agent') 
    return 'agent'; 

$scope.modes = [{ 
    value: 'client', 
    label: 'Client' 
},{ 
    value: 'agent', 
    label: 'Agent' 
}]; 

$scope.currentDataItem = data; // data is preloaded from inputs in form 

還有一個NG點擊=「clearObjectIdModal()」在切換的單選按鈕時清除模型:

$scope.clearObjectIdModal = function() { 
    $scope.currentDataItem = ""; 
} 

的問題是,每次當單選按鈕被切換到塞萊時間ct值會動態變化,其中第一個選項的值將變爲undefined。因爲在構建這些選項的數組中沒有這樣的object_id(這是不存在的id,所以繪製了一個空的字段)。
也就是說,有所有的作品。但是select中的第一個選項(切換到另一個單選按鈕之後)呈現爲空字符串。
有想法,如何解決?

回答

0

我不確定我是否正確理解您的問題,但我會建議一些改進。

  1. setFile功能改成如下

    $ scope.setFile =函數(){$回報scope.data.mode;}

我還沒有看到結束在你的代碼中你的函數的括號。此外,如果你的功能只會返回data.mode那麼爲什麼需要這個功能?

  • 我建議初始化data對象正確像:

    $ scope.data = {模式: '客戶'};

  • 更改clearObjectIdModal功能:

    $ scope.clearObjectIdModal =功能(模式) {$ scope.currentDataItem = 「」; $ scope.data.mode = mode; }

  • ,並在你的HTML使用它作爲ng-click="clearObjectIdModal(button.mode)"

    +0

    Tsungur,thaks爲您解答您的時間。但我昨天自己解決了這個問題!) –

    0

    所以在功能clearObjectIdModal()我說:

    $scope.clearObjectIdModal = function() { 
        if ($scope.e_data["mode"] == 'client') { 
        if ($scope.customersListArr.length > 0) { 
         $scope.currentDataItem.object_id = $scope.customersListArr[0]['id']; 
        } 
        } 
        else if ($scope.e_data["mode"] == 'agent') { 
        if ($scope.agentsListArr.length > 0) { 
         $scope.currentDataItem.object_id = $scope.agentsListArr[0]['id']; 
        } 
        } 
    
    } 
    

    並在此之後,當我改變單選按鈕在當前的第一個選項選擇(每次更改)都不會爲空。

    而且具有附加空期權問題能夠解決,當你添加一個標題列表中的第一項:與

    <option value="" disabled>Select</option>