我的指令范围定义有什么问题?

时间:2016-04-03 04:08:46

标签: angularjs angularjs-directive scope

我的表单中有几个<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 个答案:

答案 0 :(得分: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 :(得分:1)

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

  1. 添加父范围对象指令。您可以使用根范围,但这不是一个好习惯。请注意添加parentScope,link和cascade。
  2. &#13;
    &#13;
    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);
            }
          };
        }
     };
    });
    &#13;
    &#13;
    &#13;

    2.更改指令模板以调用级联函数

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

    1. 在控制器中,使updateSubCategoryOptions函数无状态并传递一种方法来访问主子类别列表和当前选定的类别 $scope.docCntl.document.updateSubCategoryOptions = function(docCntlIn, category){docCntlIn.subCategoryOptions=docCntlIn.categorySubCategories[category];}