Ken
Ken

Reputation: 844

Nested Directives and NgModel

I feel like I'm missing a fundamental concept of Angular directives.

Referring to this Plnkr: http://plnkr.co/edit/WWp9lB6OvxHL8gyBSU5b?p=preview

I have a model of:

{
  message: string,
  value: number
}

And I have an itemEditor directive to edit that model:

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

But I want to delegate the editing of value to a custom control:

.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});
    }

  })

At current, this code gives the error:

Error: $compile:multidir
Multiple Directive Resource Contention

Commenting the replace: true will allow this code to work. However, I lose the styling instructions from the parent template. I.E: the class form-control is not merged onto the select element.

What is the angular way to make this work?

Upvotes: 0

Views: 561

Answers (1)

Rahil Wazir
Rahil Wazir

Reputation: 10142

You are calling value-picker twice here

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

The value-picker element contains value-picker attribute as well, both being treated as directive which in conflict causing multiple directive error. Remove the attribute value-picker, either call it as element or attribute. Or you can restrict the directive to a specific declaration.

Also remove ng-model from select element of value.picker.html template, which is causing another error:

Multiple directives [ngModel, ngModel] asking for 'ngModel'

So replace: true replaces and appends the current directive attributes to the root level of template element (in your case its select)

Updated Plnkr

Upvotes: 2

Related Questions