2017-03-28 167 views
1

我一直在環顧世界相當一段時間,但沒有一個甚至遠程關閉的問題,我似乎包含這個答案。角度下拉選項添加選項獲取數據

情況如下:

我使用AngularJS填充下拉(或選擇,如你所願)(^ 1.6.2)從數據庫中讀取數據。這個數據放在這個選擇使用ng-options與一切正確設置和所有。

我試圖做到的,是一個NULL選項被添加到此選項列表,但包含所獲取的數據$scope對象。

我會用一些代碼澄清:

<select ng-options="item as item.name for item in items track by item.id" 
     ng-model="forms.formDataObject.item"> 
</select> 

這會產生一個選項列表,像這樣:

<select ...> 
    <option value="1">Item 1</option> 
    <option value="2">Item 2</option> 
    <option value="3">Item 3</option> 
    ... 
</select> 

我試着用NULL選項添加到這個下拉以下Angular過濾器:

app.filter('addNullOption',() => { 
    return (input) => { 
     if (!input[0].null_option) { 
      var emptyObj = angular.copy(input[0]); 

      Object.keys(emptyObj).forEach((key) => { 
       emptyObj[key] = null; 
      }); 

      emptyObj.null_option = true; 

      input.unshift(emptyObj); 
     } 
     return input; 
    }; 
}) 

然後在中應用過濾器與其他過濾器一樣。

此方法有效,但將NULL選項添加到$scope對象,而不是僅在此下拉列表的$scope中可用。我不希望發生這種情況,因爲整個應用程序中的其他下拉列表使用相同的$scope對象來填充下拉列表,並且它們應該不是有此NULL選項可用。

概括地說,這是我的問題:我想能到NULL選項添加到預填充下拉列表中,僅特定下拉的$scope

任何人都可以引導我在正確的方向嗎?

回答

0

而不是將過濾器數據分配給相同的數組。將其分配給不同的陣列。這樣原始數組將保持不變。

<select ng-options="item as item.name for item in sampleAr = (items | filter : addNullOption) track by item.id" 
     ng-model="forms.formDataObject.item"> 
</select> 

這可能不是最好的方法來做到這一點,但我多次碰頭,但這是我唯一的解決方案。希望這有助於

angular.module("app",[]) 
 
.controller("ctrl",function($scope){ 
 
$scope.items = [{"id":1,"name":"sss","null_option":true},{"id":2,"name":"aaa"},{"id":3,"name":"fff"},{"id":4,"name":"asdas"}] 
 
$scope.sampleAr = angular.copy($scope.items) 
 

 

 
$scope.addNullOption =()=>{ 
 
return (input) => { 
 
     if (input.null_option) { 
 
      $scope.items.splice(input,1) 
 
     } 
 
     return input; 
 
    }; 
 
} 
 

 
$scope.copys = function (item){ 
 
    return angular.copy(item); 
 
} 
 
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
<div ng-app="app" ng-controller="ctrl"> 
 
<select ng-init="sampleAr = copys(items)" 
 
ng-options="item as item.name for item in sampleAr track by item.id" 
 
     ng-model="forms.formDataObject.item"> 
 
</select> 
 
<div ng-init="items = items | filter :addNullOption() "> </div> 
 
<br> 
 
{{items}} 
 
<br> 
 
<br> 
 
{{sampleAr}} 
 
</div>

+0

我已經試過你確切的解決方案,但問題依舊。 –

+0

你可以發佈'物品'數組 –

+0

它是http://i.imgur.com/8NHv0dy.png –