最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Binding ngModel to expression's value - Stack Overflow

programmeradmin3浏览0评论

I have a scenario in which the property ng-model should bind to value that es 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 es 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

I have a scenario in which the property ng-model should bind to value that es 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 es 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

Share Improve this question edited Jul 19, 2015 at 13:15 Pankaj Parkar 136k23 gold badges240 silver badges303 bronze badges asked May 1, 2015 at 17:30 miztakenmiztaken 1553 silver badges10 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

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 bination and setting that object on the scope, instead of setting field and value separately the scope.

You simply cannot set value of ng-model by using any expression. The alternative would be to change the stucture of the JSON which you returned from server.

Markup

<div ng-controller="TodoCtrl">
    <div ng-repeat="field in properties">
        <label>{{field.property}}</label>
        <input type="text" ng-model="field.value" />
    </div>{{properties}}
</div>

Code

function TodoCtrl($scope) {

    $scope.properties = [{
        property: 'PropertyFromDB',
        value: "hello world"
    }, {
        property: 'PropertyFromDB1',
        value: "hello world1"
    }]
}

Fiddle Here

发布评论

评论列表(0)

  1. 暂无评论