0

Given the following controller code

var NamesCtrl = function($scope) {
  $scope.names = ['Bamse', 'Skalman'];
  $scope.kill = function(name) {
    $scope.names.splice(indexOf(name), 1);
  }
};

Can I call the the kill function with the current name as parameter (I.e something like this)?

<div ng-repeat="name in names">
  {{name}} 
  <input type="Button" ng-click="kill(name)" value="Kill"/>
</div>
2
  • 1
    Yes and this line should be $scope.names.splice($scope.names.indexOf(name), 1); Commented Jan 3, 2014 at 15:28
  • Hehe thank you, seems it was just problems not related to angular in my code. Commented Jan 3, 2014 at 15:40

1 Answer 1

3

Yes, you can pass the name to a function in your controller, but there is an easier and more "Angular" way. You can use a built in Angular variable for ngRepeat called $index. You can use this as the index of the array element.

<div ng-repeat="name in names">
  {{name}} 
  <input type="Button" ng-click="kill($index)" value="Kill"/>
</div>

Now in your controller your kill function can be:

$scope.kill = function(index) {
    $scope.names.splice(index, 1);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.