【问题标题】:Is there a way to bind to a model from a parent scope without passing it to a directive’s isolate scope as an attribute?有没有办法从父范围绑定到模型而不将其作为属性传递给指令的隔离范围?
【发布时间】:2014-03-28 17:12:49
【问题描述】:

对于在指令模板中定义的输入,我想将其模型绑定到其父范围内的属性。由于指令的多个实例在一个页面上,因此需要一个隔离范围。我想避免必须将模型作为指令声明中的属性传递。看起来这应该是可能的;但它不起作用。

指令:

catalogApp.directive("cmFieldFilterDtv", function () {
    return {
        templateUrl: "/templates/directives/field-filter-dtv.html",
        restrict: 'E',
        scope: {},
        link: function (scope, element, attrs) {
            var field = attrs.fid;
            var fieldCamel = field.toLowerCaseFirst();
            scope.fid = 'filter' + field;
            scope.model = scope.$parent['filters.' + fieldCamel];
            scope.options = scope.$parent['configFilter' + field];
        }
    }

});

模板:

<input id="{{fid}}"
       ng-model="model"
       data-kendo-multi-select
       data-k-options="options" />

页面:

<cm-field-filter-dtv fid="PartNumber"></cm-field-filter-dtv>
<cm-field-filter-dtv fid="PartType"></cm-field-filter-dtv>
<cm-field-filter-dtv fid="Status"></cm-field-filter-dtv>

对输入的选择更改不会(通过模型绑定)推送到父范围的属性。

【问题讨论】:

  • 通常,我将指令视为功能齐全的封装单元。因此,每个人都没有“父”范围。听起来您想在代码中添加未定义的全局依赖项,我通常认为这是个坏主意。也就是说,我认为您可以将变量存储在 $rootscope 而不是 $scope;那么它应该可以在指令和包含指令的视图的控制器中访问。

标签: angularjs angularjs-directive


【解决方案1】:

为什么不能传进去?无论哪种情况,您都可以执行以下操作:

catalogApp.directive("cmFieldFilterDtv", function () {
    return {
        templateUrl: "/templates/directives/field-filter-dtv.html",
        restrict: 'E',
        scope: {},
        link: function (scope, element, attrs) {
            var field = attrs.fid;
            scope.fieldCamel = field.toLowerCaseFirst();
            scope.fid = 'filter' + field;
            scope.options = scope.$parent['configFilter' + field];
        }
    }

});

模板:

<input id="{{fid}}"
       ng-model="$parent['filters.' + fieldCamel]"
       data-kendo-multi-select
       data-k-options="options" />

【讨论】:

    【解决方案2】:

    scope.$parent 应该允许您访问父范围。看来问题可能出在这里...

    scope.model = scope.$parent['filters.' + fieldCamel];
    

    父作用域是否有一个名为'filters.' + fieldCamel 的属性(例如$scope["filters.foo"])?或者它是否有一个名为filters 的属性包含其他值(例如$scope.filters.foo)?如果是后者,则需要改为...

    scope.model = scope.$parent['filters'][fieldCamel];
    

    或者

    scope.model = scope.$parent.filters[fieldCamel];
    

    但正如其他人所提到的,您不想将指令耦合到其父范围。考虑传递所有内容。

    【讨论】:

    • filters 是一个具有fieldCamel 属性的对象字面量。然而,使用正确的语法并不能解决这个问题。我不知道为什么;但我怀疑它与 kendo-angular 库有关。相反,如果我通过scope: { model: '=' } 将模型传递给指令,它就可以工作。因为我有大约 1000 个这样的指令要声明,所以我更喜欢只传递一个属性而不是三个属性。将模型作为唯一属性传递是可行的,并且可以从中推断出其他两个参数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-12
    • 1970-01-01
    • 1970-01-01
    • 2014-07-30
    • 1970-01-01
    • 2015-05-14
    • 1970-01-01
    相关资源
    最近更新 更多