嵌套指令和NgModel

时间:2015-08-18 18:40:31

标签: angularjs angularjs-directive

我觉得我错过了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 将允许此代码工作。但是,我丢失了父模板的样式说明。 I.E:类 form-control 未合并到select元素上。

使角色有效的方法是什么?

1 个答案:

答案 0 :(得分:2)

您在这里两次致电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指令进行特定声明。

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

  

多个指令[ngModel,ngModel]要求'ngModel'

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

Updated Plnkr

相关问题