Search code examples
angularjsangularjs-directiveangularjs-model

AngularJS removing elements when values change


In my controller, I have a variable:

$scope.myVar = { "id": 13459045, "firstName": "Joe", "lastName": "McCarthy", "createdBy": 0, "status": "active", "dollarValue": 0 } 

In my page, I have input fields mapped to the variable:

<input ng-model="myVar.id" class="checknumberrange" />

The 'checknumberrange' class is a directive that parses the input value to set a numeric value in the input field and model. While working on this directive, some of the elements in the variable $scope.myVar would be removed from the variable.

$scope.myVar = { "firstName": "Joe", "lastName": "McCarthy", "createdBy": 0, "status": "active", "dollarValue": 0 } 

In the case of the directive, I found that the values were being removed when a return value was not being provided, but you would think that it would set the value of that key to null, not remove the pairing from the variable altogether. This has happened in other parts of my project, and while the value will come back (only to potentially be removed again) when you write in the input field, I don't understand why this is happening. Using angular 1.2.0 rc3, the following html:

<input ng-model="myVar.dollarValue" ng-blur="myVar.dollarValue=myVar.dollarValue.toFixed(2)" />

Would not allow me to change the value. Changing the value would immediately remove the pairing from the variable, and if you put the focus on the input field and then elsewhere, the first time, the field will update from '0' to '0.00', and the second time will result in the pairing being removed.

I really want to understand why pairings are being removed so I can prevent this from happening in my work.


Solution

  • Angular parses what you put for ng-blur and it can't handle all javascript. Try using a function created in your controller (plnkr):

    $scope.onBlur = function()
    {
      $scope.myVar.dollarValue = Number($scope.myVar.dollarValue).toFixed(2)
    }
    

    HTML:

    <input ng-model="myVar.dollarValue" ng-blur="onBlur()" />