Peter Boomsma
Peter Boomsma

Reputation: 9808

Store value from model in a property

I have an input field:

Name: <input ng-model="query"
             ng-change="vm.returnQuery(query)" 
             ng-model-options="{debounce: 1000}" />

And I want to return the inputvalue into a console.log

In my typescript class I have this field

_query: string;

These get/set properties:

get query() {
    return this._query
}

set query(value: string) {
    this._query = value;
}

And this function,

returnQuery(query) {
    console.log('Query: ' + this._query + ' ' + query);
}

When I enter a value like something into the input the console log returns:

Query: undefined something

So how do I pass the value from the model through the get/set into the _query field?

Upvotes: 3

Views: 439

Answers (1)

Radim K&#246;hler
Radim K&#246;hler

Reputation: 123861

Would be nice to see more of your code, but let's expect that your controller (vm) is defined like this:

export class myController
{
    static $inject = ["$scope"];
    constructor(protected $scope){
    }

    _query: string;
    get query() {
        return this._query
    }

    set query(value: string) {
        this._query = value;
    }   

    returnQuery(query) {
        console.log('Query: ' + this._query + ' ' + query);
    }
}

and if this controller is assigned to directive with settings

...
controller = myController;
controllerAs = "vm";
...

Then the issue with element snippet is missing vm

// instead of this
<input ng-model="query" 
    ng-change="vm.returnQuery(query)" 
    ng-model-options="{debounce: 1000}" />

// bind this way
<input ng-model="vm.query" 
    ng-change="vm.returnQuery(vm.query)" 
    ng-model-options="{debounce: 1000}" />

Upvotes: 1

Related Questions