0

Hi I am new to Angularjs please help i am trying to create a dynamic form field my html is like this

<div ng-repeat="cb in categories">
  <div ng-repeat="choice in cb.choices">
    <input type="text" ng-model="choice.req_goods">
    <input type="text" ng-model="choice.qty">
    <button ng-hide="$first" ng-click="removeChoice($parent.$index,$index)">-</button>
  </div>
  <button type="button" ng-click="addNewChoice($index)">+</button>
</div>

js

$scope.categories = [
{
  "id":1,
   "name":"Furniture & Fixture",
   "choices":[
   {
      "req_goods":"table",
       "qty":"4"
    }]
 },
 {
   "id":2,
   "name":"Miscellaneous Property",
   "choices":[
   {
      "req_goods":"others",
      "qty":"6"
   }]
}];

$scope.addNewChoice = function(id){
            $scope.categories.choices[id].push({});
};

I want to add choices dynamically when user click add button. I tried above addNewChoice() function but it gives error angular.min.js:114 TypeError: Cannot read property '0' of undefined" please help i am really tense as i am trying this from yeterday. thank you

3
  • 2
    try $scope.categories[id].choices.push({ "req_goods":"", "qty":"" }); Commented Sep 2, 2016 at 11:34
  • exactly thank you can you help me removing (splice) the array please Commented Sep 2, 2016 at 11:40
  • i did it $scope.categories[parent_id].choices.splice(id,1); thank you Commented Sep 2, 2016 at 11:44

2 Answers 2

2

Change it to

    $scope.categories[id].choices

it will correct your error

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

Comments

1

As @Ranjith J said, you must change your code to

$scope.categories[id].choices.push({})

When you pass $index as a parameter in ng-click="addNewChoice($index)", you are referring to the categories index. So it makes sense to use your id parameter to access the right category.

See this JSFiddle for a working example.

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.