Dynamically add property to object in angularjs ng-repeat

Question

I have a list of object and iterating that list using ng-repeat to generate table row. each td contains source name and checkbox. I want to bind the checkbox with a property which is not available into list. how that is possible? The list is like that:-

scope.reasons = [
        {sourceName:'Lack of rainfall'},
        { sourceName: 'Change in land use' },
        {sourceName:'Change in Land Cover'}
        ];

and the HTML code is like that:-

<table>
  <tr ng-repeat="source in reasons">
    <td>{{source.sourceName}}</td>
    <td><input type="checkbox" ng-checked="source.postAdequate"></td>
  </tr>
</table>

Show source
| html   | angularjs   | angularjs-ng-repeat   2017-01-02 06:01 4 Answers

Answers ( 4 )

  1. 2017-01-02 06:01

    You can do this using the ng-model attribute, ng-change is just for the checking purposes that is change detection.

    <table>
        <tr ng-repeat="source in reasons">
          <td>{{source.sourceName}}</td>
          <td>
            <input type="checkbox" ng-model="source.postAdequate" ng-change="changeDet()">
          </td>
        </tr>
      </table>
    

    Demo Fiddle

    Hope this helps

  2. 2017-01-02 06:01

    Using ng-model instead of ng-checked will add property internally when checkbox is changed

    <input type="checkbox" ng-model="source.postAdequate"></td>
    

    If you must have that property on all objects iterate the array and add it

    scope.reasons.forEach(function(item){
       item.postAdequate = false
    })
    
  3. 2017-01-02 06:01

    Try this:

    <input type="checkbox" ng-model="source.postAdequate">
    

    See here jsfiddle link:

    https://jsfiddle.net/avnesh2/5cpm48tc/2/
    

    But it will add source.postAdequate: true/false only if you click, remains objects will remains same.

    So if you want to add source.postAdequate: true/false in all add in $scope.reasons before only.

    Hope this will help you.

  4. 2017-01-02 06:01

    Can you loop the scope object once to initially set postAdequate:false for all items. Then bind that object in checkbox ng-model.

            angular.forEach($scope.reasons, function(e,i){
              e.postAdequate = false;
            });
    

    html code

    <table>
    <tr ng-repeat="source in reasons">
    <td>{{source.sourceName}}</td>
    <td>
    <input type="checkbox" ng-model="source.postAdequate" ng-click="clickfunction(source.postAdequate)">
    </td></tr>
    </table>
    
◀ Go back