AngularJS ng-options inside custom directive which is inside ng-repeat

自作多情 提交于 2019-12-11 10:25:40

问题


Could you help me to find a way to set and get select element values which are placed inside my custom directive.

This is what I have:

 <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>

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) {
        }
    }
});

Thank you.

Demo: Fiddle


回答1:


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>

To set the status, just bring the Status filled in the JSON.

// ...
.controller("MyCtrl", function($scope) {
  $scope.categories = [{Id:1, Name: "Category1", Status: 1}, {Id: 2, Name: "Category2"}];
// ...

Obviouslly, to get user's selection, just grab the category.Status property. Here's the updated fiddle.

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: ...}.



来源:https://stackoverflow.com/questions/15583772/angularjs-ng-options-inside-custom-directive-which-is-inside-ng-repeat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!