Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to give value dynamically for ng-model in angularjs?

Tags:

angularjs

Here I am generating an html element dynamically using ng-repeat eg

<div ng-repeat="type in types">
    <input  type="checkbox" ng-model="{{type}}" />{{ type }}
</div>

I want to set the type value for ng-model. Is it possible or else I want to set that type value for ng-true-value like this

<div ng-repeat="type in types">
    <input  type="checkbox" ng-model="{{type}}" ng-true-value="{{type}}" />{{ type }}
</div>
like image 884
JSAddict Avatar asked Dec 21 '12 11:12

JSAddict


2 Answers

Since ng-repeat creates a child scope for each type/item/iteration, we need to associate the ng-model for each type with the parent scope, rather than the child scope. One way to do that is to use $parent:

<input type="checkbox" ng-model="$parent[type]">{{ type }}

If $scope.types is defined like in @Alex's answer, then properties typeOne, typeTwo, and typeThree will appear on the parent scope if the corresponding checkbox is clicked, and the value of the property will be true. If a checked checkbox is clicked again, the property remains, and the value will switch to false. Your code would therefore have to check for non-existent properties and for properties that exist with the value set to true or false. That's a little messy.

I would prefer to predefine an array of objects on the parent scope, where each object has the type (name), and a boolean to indicate if it is selected or not:

$scope.types = [ 
  {name: 'typeOne', selected: false},
  {name: 'typeTwo', selected: false},
  {name: 'typeThree', selected: false}];

Then, $parent is not required (because the value of "type" will be a reference to the parent object, rather than a copy of the parent property's (primitive) value):

<input type="checkbox" ng-model="type.selected">{{ type.name }}

See also What are the nuances of scope prototypal / prototypical inheritance in AngularJS? to learn more about ng-repeat and child scopes.

like image 92
Mark Rajcok Avatar answered Oct 23 '22 11:10

Mark Rajcok


You can store the dynamic values into one of the $scope's properties as follows:

function DynamicController($scope) {
    $scope.types = [
        "typeOne",
        "typeTwo",
        "typeThree"        
    ];
    $scope.typeValues = {};
};

<div ng-app ng-controller="DynamicController">
    <div ng-repeat="type in types">
        <input  type="checkbox" ng-model="typeValues[type]" ng-click="show()" /> {{ type }}
    </div>

    <h3>Values</h3>
    <div ng-repeat="type in types">
        {{ type }} : {{ typeValues[type] }}
    </div>
</div>

You can then check your values via your typeValues property of your scope.

var i,
    length = $scope.types.length;

for (i = 0; i < length; i++) {
    console.log($scope.types[i] + " : " + $scope.typeValues[$scope.types[i]]);
}            
like image 23
Alex Klock Avatar answered Oct 23 '22 11:10

Alex Klock