Maksim Nesterenko
Maksim Nesterenko

Reputation: 6213

How to pass anything from DOM-element into function defined in $scope

Example:

<div ng-repeat="obj in objList">
    <input type="text" id="obj_{{obj.id}}"/>
    <button ng-click="removeRow(NEED PARAM HERE)">Remove</button>
</div>

I could use button's id or maybe parent's, but I dont know exactly how.

And second similar case: when I want get some value from input, for example. How can I do it?

Upvotes: 1

Views: 180

Answers (2)

Joshua Powell
Joshua Powell

Reputation: 974

A little hard to follow your question, but are you trying to pass the value from the text field to the function so you can remove the row from the list?

If that is true then the you want to do something like this.

You'll want to use the ngRepeat track by functionality. See https://docs.angularjs.org/api/ng/directive/ngRepeat

HTML

<div ng-repeat="obj in objList track by $index">
  <input type="text" id="obj_{{obj.id}}" />
  <button ng-click="removeRow($index)">Remove</button>
</div>

At that point you're just using basic Javascript splice functionality to remove an item from an Array by index. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

JS

 $scope.removeRow = function($index) {
  $scope.objList.splice($index, 1);
};

See also AngularJS How to remove an Item from scope

Upvotes: 3

deonclem
deonclem

Reputation: 880

Just pass obj in your function, and then remove the object obj from objList in your controller, it will disappear from your view, that's how angular's data binding works :

<div ng-repeat="obj in objList">
  <input type="text" id="obj_{{obj.id}}"/>
  <button ng-click="removeRow(obj)">Remove</button>
</div>

And in you controller:

$scope.removeRow = function(obj) { 
  var index = $scope.objList.indexOf(obj);
  $scope.objList.splice(index, 1);     
}

Upvotes: 3

Related Questions