1

I want to add input field dynamically and ng-model must be in the below structure. I also want to delete items from array.

Expected Json

   {
       "Animals": {
            "animal": [ "dog","cat","lion"  ]
        }
   }

View

  <div ng-repeat="x in selected.Animals.animal">
     <button ng-hide="$first" ng-click="removeChoice($index)">remove</button>
     <input type="text" ng-model="x"/>
     <button ng-show="$last" ng-click="addNewChoice(x)">addnew</button>
 </div>

Controller

$scope.selected={};
$scope.selected.Animals= {};
$scope.selected.Animals.animal=[""];

$scope.addNewChoice = function (x) {
    $scope.selected.Animals.animal.push(x);
};

$scope.removeChoice = function (index) {
    $scope.selected.Animals.animal.splice(index, 1);
};

Here is the workarea

4
  • What is the question? Commented Dec 26, 2015 at 12:44
  • how to insert items to the above json like structure ? Commented Dec 26, 2015 at 12:45
  • 1
    Do you looking for something like this jsbin.com/jexujosuro/1/edit?html,js,console,output? Commented Dec 26, 2015 at 12:48
  • yaa thanks a lot. Is there any way to avoid the empty string inside the array ? Commented Dec 26, 2015 at 12:55

1 Answer 1

1

You misused $first and $last with ng-show and ng-hide. Also, it is recommended the use ng-if if possible.

At first you should use track by for ng-repeat at least for performance reason. In your case, adding duplicate animal names will cause violation of key uniqueness of repeater.

I suggest the following code as a possible solution

Controller

angular.module('myApp',[])
.controller('myController', function($scope){
  this.x = "";

  this.selected={};
  this.selected.Animals= {};
  this.selected.Animals.animal =[];

    this.addNewChoice = function (x) {
        this.selected.Animals.animal.push(x);
      this.x= "";
    };

    this.removeChoice = function (index) {
        this.selected.Animals.animal.splice(index, 1);
    };
});

View

<body ng-app="myApp" ng-controller="myController as ctrl">

  <input type="text" ng-model="ctrl.x"/>
  <button ng-click="ctrl.addNewChoice(ctrl.x)" ng-disabled="!ctrl.x">addnew</button>

  <div ng-repeat="s in ctrl.selected.Animals.animal">
    <button ng-click="ctrl.removeChoice($index)">remove</button>
    <input type="text" ng-model="s" disabled/>
  </div>

  <pre>{{ctrl.selected | json}}</pre>
</body>

Here is the JSBin

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks you so much :)

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.