Binding ng-repeat and ng-model in controller

2019-08-03 06:45发布

问题:

This is my first post on here so bear with me, I'm fairly new to AngularJS as well. I'm trying to build a form with ng-repeat and having trouble wrapping my head around the angular stuff.

JS in controller:

$scope.myCurrentAssets = {
        cash_equiv: {name: 'Cash & Equivalents', value: 0, tbi: 41},
        invest: {name: 'Short Term Investments', value: 0, tbi: 42},
        notes_rec: {name: 'Notes Receivable', value: 0, tbi: 43},
        account_rec: {name: 'Accounts Receivable', value: 0, tbi: 44},
        inventory: {name: 'Inventory', value: 0, tbi: 45},
        prepaid: {name: 'Prepaid Expenses', value: 0, tbi: 46},
        other: {name: 'Other Current Assets', value: 0, tbi: 47}
    };

HTML:

<div class="row" ng-repeat="(keyAssets, valueAssets) in myCurrentAssets">
     <span>{{valueAssets.name}}</span>
     <input data-name="myCurrentAssets.{{keyAssets}}"
          data-ng-model=""
          data-placeholder="{{valueAssets.value}}"
          data-ng-change="compute()"
          />
</div>

The problems I'm having are:

  1. trying to get the 'data-ng-model' set to something unique in each instance of the ng-repeat

  2. how do I access the value of the input field from the compute() function?

回答1:

trying to get the 'data-ng-model' set to something unique in each instance of the ng-repeat

You can use list[key][value] that will be different per item in ng-repeat

how do I access the value of the input field from the compute() function?

Generally you can use ng-model that automatically fetches input data.

<div class="row" ng-repeat="(keyAssets, valueAssets) in myCurrentAssets">
     <span>{{valueAssets.name}}</span>
     <input data-name="myCurrentAssets[keyAssets]['name']"
          data-ng-model="myCurrentAssets[keyAssets]['value']"
          data-placeholder="myCurrentAssets[keyAssets]['value']"
          data-ng-change="compute(myCurrentAssets[keyAssets]['value'])"     
          /> 
</div>

Demo Fiddle