A.S.F Studio A.S.F Studio - 4 months ago 9
Javascript Question

Changing the model value from the callback function

I have the following input

<input id="mainOdd1Id" type="number" ng-model="data.mainOdd1" min="0" step="any" ng-attr-placeholder="{{data.mainOdd1}}" ng-focus="focus($event)" ng-blur="blur($event)">


And the following function which execute on blur

$scope.blur = function($event){

var id = $event.target.getAttribute('id');

switch(id) {
case "mainOdd1Id":
$scope.data.mainOdd1 = func($scope.data.mainOdd1);
break;
case "mainOdd2Id":
$scope.data.mainOdd2 = func($scope.data.mainOdd2);
break;
case "bkOdd1Id":
$scope.data.bkOdd1 = func($scope.data.bkOdd1);
break;
case "bkOdd2Id":
$scope.data.bkOdd2 = func($scope.data.bkOdd2);
break;
default:
break;
}
}


I would like to avoid the switch command by getting a "pointer" to the data field by the id and changing it. (*pointer = function(*pointer))

Is that possible?

Thanks

Answer

You can access properties by name using bracket notation.

Suppose you have a variable containing property name propertyName. Then you can access some object obj property like this var propertyValue = obj[propertyName].

This should do the trick. If you remain the same naming convention that element's id is just propName + 'Id'

$scope.blur = function($event){
  // convert mainOdd1Id -> mainOdd1
  var id = $event.target.id.replace(/Id$/, '');

  if(id in $scope.data) { // check if prop is in scope.data
     $scope.data[id] = func($scope.data[id]); // perform update
  }
}

or you can pass correct property name from within template

<input id="mainOdd1Id" ... ng-focus="focus('mainOdd1')"  ng-blur="blur('mainOdd1')">


$scope.blur = function(propertyName){
  $scope.data[propertyName] = func($scope.data[propertyName]);
}
Comments