Jason
Jason

Reputation: 4130

Passing An Ng-Model Value to A Directive

I've looked at the previous answers, but I'm not sure if they are the answer I need or not.

I have a directive, let's call it "selectValue". A value can have a default, let's call it "$scope.default".

The directive will look like this in one place:

<select-value ng-model="data.input" controlId="inputSelector" />

But it will look like this in another:

<select-value ng-model="myValue" controlId="inputSelector" />

I do not have the option of making the ng-model inputs the same; they are used in different places and this is a legacy code base.

Here is the definition of the directive:

    .directive('selectValue', ['$timeout', function($timeout) {

    const directive = {
        restrict: 'E',
        scope: {
            controlId: '@',  
            model: '=?'
        },
        controller: 'selectValueCtrl',
        template: '<input id="{{controlId}}" name="{{controlId}}" placeholder="Enter Value" type="text" ng-model="model" />'
    };

    return directive;
}

The question: what do I do to be able to enter different inputs in the "model" attribute of the <select-value> to have it access different scope variables?

Edit: the referenced "duplicate" question refers to setting a value for ng-click, not referencing ng-model in a form control.

Upvotes: 0

Views: 108

Answers (1)

Shaquan Kelly
Shaquan Kelly

Reputation: 113

From what I can tell, it looks as though you are trying to pass defaults with preset values. The problem you are facing is your select-value element is using the ng-model directive in an attempt to pass the data however your binding in your directive is 'model'.

In order to fix this issue, simply change the 'ng-model' to 'model' and your bindings should then work.

In the end, your element should look like so:

<select-value model="myValue" controlId="inputSelector" />

as opposed to:

<select-value ng-model="myValue" controlId="inputSelector" />

Upvotes: 2

Related Questions