Samuel E.
Samuel E.

Reputation: 2422

Bind variable to field on focus in angular

I'm using Angular 1.6.2 for a personal project for learning the framework, and I couldn't figure out a way to solve this problem:

I have a variable that gets updated often(like once a second or less) and I have two input text fields in the view. I want the variable to update the input(and another variable) only when it is focused.

For sake of better UX I now updated the view a little bit, so now every Text-Input has a Radio-Button alongside(since sometimes the user might want the value to be updated but he'll need to click outside the field).

Inside the controller:

$interval(function () {
    // This gets the updated value from an external source/code.
    $scope.updatingValue = updatingValueFunc();
}, 1000);

$scope.fields = [
    { first: 12323, second: 1430,}
];

Html:

<div class="field-wrap">
    <input type="radio" name="current-bind" value="answer.end">
    <input type="number" ng-model="answer.second">
</div>
<div class="field-wrap">
    <input type="radio" name="current-bind" value="answer.start">
    <input type="number" ng-model="fields.first">
</div>

Upvotes: 1

Views: 375

Answers (1)

Cameron Rodriguez
Cameron Rodriguez

Reputation: 146

Angular has a ng-focus hook you can use to call your update function.

<input type="radio" name="current-bind" value="answer.end" ng-focus="updateValue()"/>

and in your js you can create a function to match it

$scope.updateValue = function(){
   $scope.updatingValue = updatingValueFunc();
}

You can also use ng-click if you want the function to run on click instead of on focus.

Upvotes: 1

Related Questions