benhowdle89
benhowdle89

Reputation: 37474

Angular.js - prefill input with one property, but set ng-model to different property

I have my input:

input(ng-model='amount' ng-init='amount = (amount == 0) ? total : amount')

So I need the user-inputted value to be saved to amount, however, when the page loads, if amount happens to be zero, then prefill it with total.

All works fine, however, I have an interval running to refresh the data from the server, so when that refresh happens, I'm guessing the model value amount changes, and it sets the input to "0" (if amount was zero). How can I resolve this?

Upvotes: 2

Views: 1008

Answers (3)

Valery Bugakov
Valery Bugakov

Reputation: 355

You can use optional assignment on you model in controller.

$scope.myModel = $scope.myModel || $scope.prefilled

I created codeopen example of it: http://codepen.io/skymk/pen/vOyPWB?editors=101

Upvotes: 0

PSL
PSL

Reputation: 123739

Your issue is with the usage of ng-init, first of all it is not appropriate to use it for anything else other than aliasing ng-repeat special properties like $index, $first etc... ng-init'ed expressions are not watched during every digest cycle for changes. Moreover viewvalue update is done when ng-model is updated. So you do not see it getting evaluated during a later digest cycle. Instead of using ng-init just set the ng-model itself in the controller to the default value.

 $scope.amount = $scope.amount || $scope.total;

Or you could as well use getter setter option of the ng-model.

Upvotes: 1

Riad Baghbanli
Riad Baghbanli

Reputation: 3319

Create new variable inputAmount, bind it to your input.

input(ng-model='inputAmount' ng-init='inputAmount = (amount == 0) ? total : amount')

Upvotes: 0

Related Questions