你能帮我找到一种方法来设置和获取放置在我的自定义指令中的选择元素值吗?
这就是我所拥有的:
<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 以最终获得类似[{CategoryId:1,StatusId:2},{CategoryId:2,StatusId:3}]
. 如果 selectedStatus 已经初始化,我想查看相应类别的选择状态,这意味着我还需要输入值,而不仅仅是读取它们。
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) {
}
}
});
谢谢你。
演示:小提琴