自定义指令内AngularJS NG选项是NG-重复内 [英] AngularJS ng-options inside custom directive which is inside ng-repeat
问题描述
你能帮我找到一种方法来设置和获取它放在我的自定义指令内选择元素的值。
Could you help me to find a way to set and get select element values which are placed inside my custom directive.
这是我有:
<body ng-app="myApp">
<div ng-controller="MyCtrl">
<div ng-repeat="category in categories">
{{category.Name}}:
<status-selector items="statuses" ng-model="selectedStates[status.Id]"></status-selector>
</div>
</div>
</body>
我有两个数组:类别和状态。每个类别可以有其自己的状态。当选择一个类别的地位,它应该被保存到selectedStatus终于有类似 [{类别ID:1,StatusId:2},{类别编号:2,StatusId:3}]
。在情况下,如果selectedStatus已初始化,我希望看到的状态选择相应的类别,这意味着我也需要把价值观,而不仅仅是阅读。
I have two arrays: categories and statuses. Each category can have its own status. When a status for a category is chosen, it should be saved to selectedStatus to finally have something like [{CategoryId:1,StatusId:2},{CategoryId:2,StatusId:3}]
. In case if selectedStatus was already initialized, I would like to see chosen statuses for corresponding categories, means that I also need to put values, not just read them.
myApp
.controller("MyCtrl", function($scope) {
$scope.categories = [{Id:1, Name: "Category1"}, {Id: 2, Name: "Category2"}];
$scope.statuses = [{Id: 1, Name: "Low"}, {Id: 2, Name: "Normal"}, {Id: 3, Name: "High"}]
$scope.selectedStates = {};
})
.directive('statusSelector', function() {
return {
restrict: 'E',
replace: true,
scope: { items: '=', ngModel: '='},
template: '<span><select class="select" ng-options="obj.Id as obj.Name for obj in items" ng-model="ngModel"></select></span>',
link: function(scope, element, attrs) {
}
}
});
感谢您。
演示:小提琴
推荐答案
您应该有自己的分类模型 NG-模型
。它可能更有意义。
You should have your own category model as ng-model
. It probably make more sense.
<status-selector items="statuses" ng-model="category.Status"></status-selector>
要设置状态,只需将状态填补了JSON
。
// ...
.controller("MyCtrl", function($scope) {
$scope.categories = [{Id:1, Name: "Category1", Status: 1}, {Id: 2, Name: "Category2"}];
// ...
Obviouslly,让用户的选择,只要抓住了 category.Status
属性。这里的更新拨弄。
此外,只需一个侧面一角。你似乎来自净背景,你在哪里使用Pascal大小写。在JavaScript中,这是常识,使用骆驼情况下,相反,所以你必须 {ID:...,状态:...}
而不是 {ID:...,状态:...}
Also, just a side tip. You seem to come from a .Net background, where you're used to Pascal case. In javascript, it's common sense to use camel case, instead, so you'd have {id: ..., status: ...}
instead of {Id: ..., Status: ...}
.
这篇关于自定义指令内AngularJS NG选项是NG-重复内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!