Search code examples
javascriptangularjsangularjs-scopeangularjs-ng-model

Binding ngModel to expression's value


I have a scenario in which the property ng-model should bind to value that comes from database as a part of business logic.

For simplicity, I have created this example

function TodoCtrl($scope) {
    $scope.field1 = "PropertyFromDB";
    $scope.PropertyFromDB = "hello world";
}

<div ng-app>
  <h2>ngModel BINDING EXAMPLE</h2><br/>
  <div ng-controller="TodoCtrl">
      <div ng-init="imod = field1">
          <input type="text" ng-model="imod"></input>
      </div>
  </div>
</div>

In this example, field1 is the value which will be property that comes from DB (i.e. PropertyFromDB) and ng-model should bind to PropertyFromDB instead of field1. So, its like I want to evaluate expression inside expression syntax of ng-model but I am unable to do so.

Thanks


Solution

  • You can refer to the current scope with this and read its property, like:

    <div ng-init="imod = field1">
      <input type="text" ng-model="this[imod]"></input>
    </div>
    

    but it is a very unusual and inconvenient way to create a View Model.

    I suggest creating a better structure/object that contains the field/value combination and setting that object on the scope, instead of setting field and value separately the scope.