A.S.F Studio A.S.F Studio - 1 year ago 61
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);
case "mainOdd2Id":
$scope.data.mainOdd2 = func($scope.data.mainOdd2);
case "bkOdd1Id":
$scope.data.bkOdd1 = func($scope.data.bkOdd1);
case "bkOdd2Id":
$scope.data.bkOdd2 = func($scope.data.bkOdd2);

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?


Answer Source

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]);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download