【问题标题】:AngularJS ng-options inside custom directive which is inside ng-repeatAngularJS ng-options 在 ng-repeat 中的自定义指令中
【发布时间】:2013-03-23 20:46:30
【问题描述】:

您能帮我找到一种方法来设置和获取放置在我的自定义指令中的选择元素值吗?

这就是我所拥有的:

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

谢谢。

演示:Fiddle

【问题讨论】:

  • 谢谢阿伦·P·约翰尼。您在 Fiddle 中的演示帮助我了解问题出在 [status.Id] 中,我必须使用 [category.Id]。谢谢!

标签: angularjs angularjs-directive angularjs-ng-repeat


【解决方案1】:

您应该拥有自己的类别模型ng-model。这可能更有意义。

<status-selector items="statuses" ng-model="category.Status"></status-selector>

要设置状态,只需带上JSON中填写的Status即可。

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

显然,要获得用户的选择,只需获取category.Status 属性。这是updated fiddle

另外,只是一个小提示。您似乎来自 .Net 背景,习惯于 Pascal 案例。在 javascript 中,使用驼峰式大小写是常识,因此您将使用 {id: ..., status: ...} 而不是 {Id: ..., Status: ...}

【讨论】: