【问题标题】:Nested Directives and NgModel嵌套指令和 NgModel
【发布时间】:2015-11-11 20:30:36
【问题描述】:

我觉得我缺少 Angular 指令的基本概念。

参考此 Plnkr:http://plnkr.co/edit/WWp9lB6OvxHL8gyBSU5b?p=preview

我有一个模型:

{
  message: string,
  value: number
}

我有一个 itemEditor 指令来编辑该模型:

  .directive('itemEditor', function() {
    return {
      replace: true,
      templateUrl: 'item.editor.html',
      require: 'ngModel',
      model: {
        item: '=ngModel'
      }
    };
  })

但我想将值的编辑委托给自定义控件:

.directive('valuePicker', function() {
    return {
      replace: true, // comment this to make it work
      templateUrl: 'value.picker.html',
      require: 'ngModel',
      scope: {
        ngModel: '='
      },

      controller: Controller
    };

    function Controller($scope, Values) {
      $scope.values = Values;
      console.log({scope:$scope});
    }

  })

目前,此代码给出错误:

Error: $compile:multidir
Multiple Directive Resource Contention

评论 replace: true 将允许此代码工作。但是,我丢失了父模板中的样式说明。 IE:类 form-control 没有合并到选择元素上。

实现这项工作的角度方式是什么?

【问题讨论】:

    标签: angularjs angularjs-directive


    【解决方案1】:

    你在这里打了两次value-picker

    <value-picker class="form-control" style="width:100%" name="item" value-picker ng-model="item.value"></value-picker>
    

    value-picker 元素也包含value-picker 属性,两者都被视为指令,冲突导致多指令错误。删除属性value-picker,将其称为元素或属性。或者你可以restrict 指令到一个特定的声明。

    同时从value.picker.html 模板的select 元素中删除ng-model,这会导致另一个错误:

    多个指令 [ngModel, ngModel] 要求“ngModel”

    所以replace: true 替换当前指令属性并将其附加到模板元素的根级别(在您的情况下为select

    Updated Plnkr

    【讨论】:

    • 啊..我明白了。因此,ng-model 也被合并到模板中。优秀。非常感谢!
    猜你喜欢
    • 2015-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-21
    • 2014-08-23
    • 2017-06-27
    • 2017-01-13
    相关资源
    最近更新 更多