Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS Targeting elements in current iteration in ng-repeat

I am sure this question has been answered numerous times in one form or another, however I am not sure what to search for to find the solution.

Say we have a simple ng-repeat:

<div ng-repeat="item in items">
   <input type="text" value="{{item.name}}">
   <a ng-click="getTxtBoxVal(whatDoIPassInHere)">Get Text Box Value</a>
</div>

in the javaScript file:

   function $scope.getTxtBoxVal(val) {
       alert(val)
   }

Basically I want to know what should get passed in the whatDoIPassInHere parameter, which in jquery would be something like: $(this).siblings(input).val()


I do have a workaround which is to give each textbox a unique ID:

<input type="text" id="myTextBox_{{index}}" value="{{item.name}}>

and target it with the unique ID, but I am sure there's a more elegant way to handle this

like image 320
Sammy Avatar asked Jul 23 '15 16:07

Sammy


1 Answers

You're not associating the input with a model, so angular has no idea how to reference the value. See this plunkr for how to accomplish what you are asking.

Controller

$scope.things = [
    {
      'name': 'apple',
      'value': '12',
      'isTasty': true
    },
    {
      'name': 'tire',
      'value': '7',
      'isTasty': false
    },
    {
      'name': 'carrot',
      'value': '9',
      'isTasty': false
    },
    {
      'name': 'cake',
      'value': '1',
      'isTasty': true
    }
  ];

  $scope.getVal = function (value) {
    alert(value);
  };

View

<div ng-repeat="item in things">
      <input type="text" ng-model="item.name" value="{{item.name}}">
      <a href="#" ng-click="getVal(item.name)">Get Text Box Value</a>
    </div>
like image 99
Daniel Cottone Avatar answered Sep 29 '22 07:09

Daniel Cottone