简体   繁体   中英

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?

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);     
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM