javascriptangularjsangularjs-ng-modelng-bind

ng-model does not bind within ng-repeat, while everything else does


I know there are a ton of questions already on this topic, I tried the solutions I found but it doesnt seem to work. Basically I have this directive called basicMunch that goes through an array of objects and creates some html. Everything works nicely and bind other than the ng-modal Here is the code for the directive:

>     munches.directive('basicmunches', function() {   return {
>     require: 'ngModel',
>     template:`<div class='columns'>  <div ng-repeat="mu in basicMunches" class="card column col-4 col-sm-12">
>           <div class="card-header">
>             <h4 class="card-title">{{mu.name}}</h4>
>             <h6 class="card-subtitle">{{mu.type}}</h6>
>           </div>
>           <div class="card-body">
>             {{mu.text}}
>           </div>
>           <div class="card-footer">
>             <div class="form-group">
>               <label class="form-switch">
>                 <input ng-model="mu.tag" name="{{mu.tag}}"  type="checkbox" />
>                 <i class="form-icon"></i> Turn On
>               </label>
>             </div>
>           </div>
>         </div></div>`   } });

Here is the array:

 $scope.basicMunches  = [
    {"name":"The New York TImes",
     "text":"Get the top headlines from the NYT every morning", 
     "type":"News", "tag":"nyt"
    },
    {"name":"Wall Street Journal",
     "text":"Get the top headlines from the WSJ every morning", 
     "type":"News", "tag":"wsj"
    }
];

Here is what i see in the console enter image description here

I have tried doing $parent.mu.tag and $parent.$parent.mu.tag, but that didnt work as it shouldnt have because it isnt nested in some other scope (atleast not that I know of)

I tried doing the name of the controller.mu.tag, that too doesnt work

I tried doing mu['tag'] and that doesnt work either

I tried using {{ and that doesnt work I changed it to ng-bind={{mu.tag}} and that does work It is weird to me that it works for ng-bind but it doesnt work for ng-model.... Anyhow, anyone have any ideas?


Solution

  • It seems like what you are wanting is to bind the ng-model property to the value of mu.tag, rather than to mu.tag itself.

    Due to the way that ng-model is parsed, you need to use a variation of the bracket syntax in order to make this possible. The proper syntax here is $parent[mu.tag] which will look on the $parent object for the property named by the value of mu.tag. The parent of the ng-repeat is $scope, so this ends up with the property on the correct object.

    <input ng-model="$parent[mu.tag]" name="{{mu.tag}}"  type="checkbox" />
    

    http://plnkr.co/edit/RZNDa2XVUoZp1z7QeN46?p=preview