![](/img/trans.png)
[英]How do I model this data structure in JavaScript? (AngularJS)
[英]How do I traverse model data in AngularJS?
我有一个像这样的支持JSON的下拉列表:
$scope.tradestyles = [
{"id":"1","source":"Source One","name":"Name One"},
{"id":"2","source":"Source Two","name":"Name Two"}
]
这是一个下拉列表,使用select2
,模型是所选贸易风格的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值的同级名称值?
如果我正确理解了您的问题,则需要使用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/
<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项目。
它对Underscore有依赖性,但是您可以用更长的替代方法来删除它,而不是findWhere()方法。
我相信您正在寻找的是这样的:
<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>
工作提琴 :
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.