javascript - AngularJS nested ng-repeat click & show/hide -


i've done ton of reading , research on topic past few days , have found answers, of answers question performance , necessity.

my question pertains nested ng-repeat scopes. i'm wondering best way achieve "add item" scenario adding item nested foreach.

my code

my html 2 ng-repeats , goal able add item second (nested) ng-repeat

<div ng-app="myapp">     <div class="nav" ng-controller="foodscontroller vm">         <div class="level1" ng-repeat="foods in vm.foodgroups">{{foods.name}}             <button type="button" ng-click="vm.addnewfood()">add new food</button>             <div ng-show="vm.newfoodbeingadded">                 <input type="text">             </div>             <div class="level2" ng-repeat="food in foods.foodsingroup">{{food.name}}</div>         </div>     </div> </div> 

my angular controller looks this:

app.controller('foodscontroller', function () {     var vm = this;     vm.foodgroups = [{         "name": "grains",             "foodsingroup": [{             "name": "wheat"         }, {             "name": "oats"         }]     }, {         "name": "fruits",             "foodsingroup": [{             "name": "apple"         }, {             "name": "orange"         }]     }];      vm.newfoodbeingadded = false;      vm.addnewfood = function () {         vm.newfoodbeingadded = true;     }; }); 

what should happen

the general work flow user clicks add new button , shows text box "save" button. text box & button within parent foreach. once user saves item added nested foreach (that logic isn't shown).

the issue

the issue when click "add new food" (which should show 1 of text boxes & save buttons), of text boxes show. how ensure "scoping" correctly , text box/button within parent shown?

possible solution

one answer found create child controller each nested item. example i'd have foodgroupscontroller manage logic nested foreach (because there lot more going on adding new item in real app, justified).

jsfiddle

here's jsfiddle code not function correctly.

there forked fiddle

i made few changes. fact binding ng-show single var in controller. show me or show me nothing possibility. fix it, have bind this, in food item, not in controller himself.

html :

<button type="button" ng-click="vm.addnewfood(foods)">add new food</button>     <div ng-show="foods.newfoodbeingadded" class="add-new-food">        <input type="text" placeholer="add new food">        <button type="button">save new food</button> </div> 

controller :

vm.addnewfood = function (foods) {     foods.newfoodbeingadded = true; }; 

with code, pass food in param of function, can change boolean of food only. , then, ng-show binding on boolean.


Comments

Popular posts from this blog

python - pip install -U PySide error -

arrays - C++ error: a brace-enclosed initializer is not allowed here before ‘{’ token -

cytoscape.js - How to add nodes to Dagre layout with Cytoscape -