2014-02-28 8 views
0

我有一個背襯JSON這樣的下拉:如何在AngularJS中遍歷模型數據?

$scope.tradestyles = [ 
    {"id":"1","source":"Source One","name":"Name One"}, 
    {"id":"2","source":"Source Two","name":"Name Two"} 
] 

這是下拉,使用select2,該模型是所選tradestyle的ID:

<select id="tradestyle" ui-select2 ng-model="currentTradestyle" > 
    <option ng-repeat="tradestyle in tradestyles" value="{{tradestyle.id}}"> 
     {{tradestyle.name}} 
    </option> 
</select> 

在它旁邊,我想要放置一個文本字段,其中顯示所選貿易風格的名稱,並且可以編輯 。

<input type="text" ng-model="currentTradestyle" /> 

如何將後者的模型更改爲指向所選交易方式的名稱而不是ID?換句話說,我如何遍歷範圍對象以指向所選ID值的兄弟名稱值?

回答

2

如果我正確地理解了你的問題,你需要使用ng-options來綁定到一個對象而不是一個字段。因此,它成爲

<select id="tradestyle" ui-select2 ng-model="currentTradestyle" ng-options="style.name for style in tradestyles"> 

     </select> 
<input type="text" ng-model="currentTradestyle.id" /> 
<input type="text" ng-model="currentTradestyle.name" /> 

看到這裏我的小提琴 http://jsfiddle.net/cmyworld/UsfF6/

+0

謝謝,但用戶界面,選擇2是NG選項不兼容。我希望得到一個與ui-select2兼容的答案。 –

+0

嗯,也許你可以在''ng-repeat''選項上嘗試'ng-click'並手動選擇控制器中的項目。 – Chandermani

+0

如果你在ng-repeat中添加一個ng-click,你將會創建與你重複的元素一樣多的事件處理程序,但我不認爲這是一個有效的解決方案。 – Wawy

1

我相信你所尋找的是這樣的:

<div ng-app="myApp"> 
    <div ng-controller='Ctrl'> 
     <select id="tradestyle" ui-select2 ng-model="currentTsIndex"> 
      <option ng-repeat="tradestyle in tradestyles" value="{{$index}}">{{tradestyle.name}}</option> 
     </select> 
     <input type="text" ng-model="tradestyles[currentTsIndex].name" /> 
    </div> 
</div> 

工作fiddle

+0

謝謝,這應該適用於我的情況。我會發現使用ID作爲下拉值會更優雅,而'currentTradestyle.name'看起來比'tradestyles [currentTsIndex] .name'好,但我不想對此有所信任。 –

+0

我遇到的另一個問題是Angular無法跟蹤我在編輯字段中所做的更改,並稍後更新下拉列表,而不是與我的輸入同步。 –

+0

在我的小提琴中它工作得很好。 – Wawy

2
<div ng-app="myApp"> 
    <div ng-controller='Ctrl'> 
     <select id="tradestyle" ng-model="currentTradestyle" update-model="tradestyles"> 
      <option ng-repeat="style in tradestyles" value="{{style.id}}">{{style.name}}</option> 
     </select> 
     <input type="text" ng-model="currentTradestyle.name" /> 
    </div> 
</div> 

的JavaScript :

var app = angular.module('myApp', []); 

app.controller('Ctrl', ['$scope', '$rootScope', function ($scope, $rootScope) { 
    $scope.tradestyles = [{ 
     "id": "1", 
     "source": "Source One", 
     "name": "Name One" 
    }, { 
     "id": "2", 
     "source": "Source Two", 
     "name": "Name Two" 
    }]; 
}]); 


app.directive('updateModel', function() { 
    return { 
     require: '?ngModel', 
     restrict: 'A', 
     link: function(scope, element, attrs, modelCtrl) { 
      function parser(value) { 
       if(value) { 
        return _.findWhere(scope[attrs.updateModel], {id: value}); 
       } 
      } 
      modelCtrl.$parsers.push(parser); 
     }, 
    } 
}); 

這可能會滿足您在評論中提出的問題。它在<option>中使用tradestyle.id而不是$ index,這意味着所選項目適用於集合應用了過濾器的情況。 $ parser的額外保證了tradestyle.id在應用到currentTradestyle模型屬性之前實際上變成了選定的tradestyle項目。

Theres依賴於Underscore,但您可以使用findWhere()方法的更長時間替代方法刪除它。

http://jsfiddle.net/asperry1/Zfecq/6/