DeX3
DeX3

Reputation: 5539

Understanding custom directives and ngModelController

despite the massive amounts of examples online, I simply cannot wrap my head around the correct way to use ng-model for my custom directive.

I wanted to implement a custom directive that basically is a <select> tag, with fixed options that, when selected will set booleans in the model.

In short, I want to be able to use my directive like this:

<my-directve ng-model="amodel.options"></my-directive>

This should render a select, that when the user selects an option updates amodel.options to be set accordingly:

How would I accomplish this? I got this far:

angular.module("myApp")
    .directive( "myDirective", function() {
    return {
        restrict: "E",
        replace: true,
        require: "ngModel",
        scope: {},
        template: '<select ng-model="internal">' + 
                    '<option value="0">Option A</option>' +
                    '<option value="1">Option B</option>' +
                    '<option value="2">Option C</option>' +
                  '</select>',
        link: function( scope, element, attr, ngModel ) {

            var mappings = [
                { foo: true, bar: false },
                { foo: false, bar: true },
                { foo: true, bar: true }
            ];

            scope.$watch( "internal", function( val ) {
                ngModel.$modelValue.foo = mappings[val].foo;
                ngModel.$modelValue.bar = mappings[val].bar;
            } );
        },
    };
} );

But all this does is give me the error that ng-Model is used redundantly.

I tried going along with various tutorials but none of them worked for me...

How would I do this correctly?

Thanks in advance!

Upvotes: 0

Views: 88

Answers (1)

bmleite
bmleite

Reputation: 26870

The problem is that you are setting the replace attribute to true. That means two things:

  • The directive's HTML will be replaced by the template HTML
  • All the attributes/classes from the old element will be migrated to the new one (including the ng-model)

This last step is the one that's causing the "ng-Model is used redundantly" error.

In order to fix it you just need to remove the replace attribute. Also, please have in mind that the replace attribute will be deprecated, so the sooner you stop using it, the better.

Demo

Upvotes: 1

Related Questions