2016-04-03 48 views
0

我的表格中有几个<select>字段。我想动态地加载这些选项,所以我使用ng-repeat遍历可以随数据对象一起移动的选项列表。我的指令范围定义有什么问题?

若要使此功能的可重用性,我断绝这个代码段,并创建一个指令:

的javascript:

angular.module("ngFamilyTree") 
    .directive("selectInput", function(){ 
     return { 
      restrict: "E", 
      templateUrl: "templates/directives/selectInput.html", 
      scope: { 
       element: "=", 
       options: "=", 
       change: "=" 
      } 
     }; 
    }); 

模板/指令/ selectInput.html:

<select ng-model="element" class="form-control"> 
    <option ng-repeat="(text, value) in options" value="{{value}}">{{text}}</option> 
</select> 

在主要形式中,我在各个地方使用以下指令元素:

<select-input element="docCntl.document.type" options="docCntl.document.typeOptions"></select-input> 

<select-input element="docCntl.document.category" options="docCntl.categoryOptions" change="docCntl.document.updateSubCategoryOptions()"></select-input> 

<select-input element="docCntl.document.subcategory" options="docCntl.subCategoryOptions"></select-input> 

我觉得奇怪的是,第一个例子中,我将元素设置为“docCntl.document.type”的作品完美无缺。每次我改变select的值时,对应元素的值都会在模型对象中改变。但是,第二项和第三项不会更改模型值。

此外,我已经尝试过这个,没有“更改”属性。这样做的目标是能够设置更新功能,在类别更改时更改子类别的可用选项。

注:我有意将类别选项和子类别选项存储在docCntl中而不是docCntl.document中;这就是为什么它们与可用于类型选择器的选项有所不同。

注2:在初始页面加载时,类别和子类别正确加载了正确的选项。

回答

2

你看过this吗?您可以使用ng-options指令来实现相同的结果。

您可以使用这样的事情在你的标记 -

<select ng-options="item as item.label for item in items track by item.id" ng-model="selected"></select> 

在控制器中相应的脚本应该是这样的 -

$scope.items = [{ 
    id: 1, 
    label: 'aLabel', 
    subItem: { name: 'aSubItem' } 
}, { 
    id: 2, 
    label: 'bLabel', 
    subItem: { name: 'bSubItem' } 
}]; 

希望这帮助:)

1

尝试这种解决方案http://plnkr.co/edit/wdKObUItDMqLyVx1gObS?p=preview

  1. 添加父范围对象的指令。你可以使用根作用域,但这不是一个好习惯。请注意添加parentScope,链接和级联。

ngFamilyTree.directive("selectInput", function() { 
 
return { 
 
    restrict: "E", 
 
    templateUrl: "templates/directives/selectInput.html", 
 
    scope: { 
 
     element: "=", 
 
     options: "=", 
 
     change: "=", 
 
     parentScope: "=" 
 
    }, 
 
    link: function(scope) { 
 
     scope.cascade = function(val) { 
 
     if (typeof scope.change === 'function') { 
 
      scope.change(scope.parentScope, scope.element); 
 
     } 
 
     }; 
 
    } 
 
}; 
 
});

2。改变指令模板调用级联功能

<select ng-model="element" class="form-control" ng-change="cascade()"> 
 
     <option ng-repeat="(text, value) in options" value="{{value}}">{{text}}</option> 
 
    </select>

  • 在控制器中,使updateSubCategoryOptions起作用无国籍并通过一种方式来访问主子类别列表和当前选择的类别 $scope.docCntl.document.updateSubCategoryOptions = function(docCntlIn, category){docCntlIn.subCategoryOptions=docCntlIn.categorySubCategories[category];}