i_ll_be_back i_ll_be_back - 1 month ago 17
Javascript Question

$scope methods not recognized from table AngularJS

I'm binding an array through a form using ng-repeat. Here is the code.

HTML:

<form>
<table>
<tr data-ng-repeat="x in names">
<td><textarea placeholder="New Name" ng-model="x.name" name="" ></textarea></td>
<td><button style="background:#f00;" ng-click="removeChoice(x)">-</button></td>
</tr>
</table>
</form>


Javascript:

.controller('TerrItemCtrl', function($scope){
$ionicModal.fromTemplateUrl('templates/addAddress.html', {
scope: $scope,
animation: 'animated bounceInDown',
hideDelay: 920
}).then(function (modal) {
$scope.names = [{ 'id': 'name1'}];
$scope.modal = modal;
$scope.modal.show();
});
$scope.removeChoice = function (x) {
for (i = 0; i < $scope.names; i++) {
if ($scope.names[i].id === x.id) {
$scope.names.splice(i);
break;
}
}
};
});


I have a $scope.removeChoice function in the controller of this form the html can't find it. I believe it's because of the array I'm using but this is the only way I've managed to put the (-) button on the right of the input tag. Any way to bypass this?

Answer

var app = angular.module('myApp', []);
app.controller('TerrItemCtrl', function($scope) {
  $scope.names = ["a", "b", "c"];

  $scope.removeChoice = function(index) {
    $scope.names.splice(index, 1);
  };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<form ng-app="myApp" ng-controller="TerrItemCtrl">
  <table>
    <tr data-ng-repeat="x in names">
      <td>
        <textarea placeholder="New Name" ng-model="x" name=""></textarea>
      </td>
      <td>
        <button style="background:#f00;" ng-click="removeChoice($index)">-</button>
      </td>
    </tr>
  </table>
</form>