0

In my angular.js project, I have a loop which contains a input field

<input type="text" ng-model="myColour">
<div ng-repeat="c in colors">
    <input type="text" ng-model="colour">
    <a href ng-click="asd(colour)">Click</a>
</div>

and when user click on "Click" link next to input field, I want to access that input field in my controller to set/get that field value. Following is my controller code

$scope.colors = [
    {id: 1, name: 'black', shade: 'dark'},
    {id: 2, name: 'white', shade: 'light'},
    {id: 3, name: 'red', shade: 'dark'},
    {id: 4, name: 'blue', shade: 'dark'},
    {id: 5, name: 'yellow', shade: 'light'}
];

$scope.asd = function(data){
    console.info(data);
    console.info($scope.myColour);
    console.info($scope.colour);
};

this gives me

colour input field data
my colour input field data
undefined 

Here I can not access "colour" model if it is repeated in view. So I tried to generate random model name (concatenate c.id with colour in model), I tried several way to achieve this but no luck.

Is there a way to generate random ng-model name?

OR

Is there any way to access model of input field whose "Click" link is clicked?

MKB
  • 7,587
  • 9
  • 45
  • 71

1 Answers1

1

try something like this:

<div ng-repeat="c in colors">
    <input type="text" ng-model="c.colour">
    <a href ng-click="asd(c.colour)">Click</a>
</div>

with JS:

// your collection
$scope.colors = [
    {id: 1, name: 'black', shade: 'dark'},
    {id: 2, name: 'white', shade: 'light'},
    {id: 3, name: 'red', shade: 'dark'},
    {id: 4, name: 'blue', shade: 'dark'},
    {id: 5, name: 'yellow', shade: 'light'}
];

// add a new key called 'colour' on your colors which will be the model
angular.forEach($scope.colors, function(value, key){
   $scope.colors[key]['colour'] = ""; // match node in html
});
SoluableNonagon
  • 11,541
  • 11
  • 53
  • 98