Search code examples
angularjsangularjs-ng-repeatangular-ng-if

Ng-if inside ng-repeat is not re evaluated


My users have pre assigned roles. You can assign any role to any user.

  • If the user already has the role => checkbox checked (you can uncheck to disable the role)

  • If the user has not the role : you have the "add" button to add the role to the user. When adding the role, the checkbox should appear (and checked)

  • {{user.name}} {{role}}

$scope.users = [];
$scope.roles = ["a", "b", "c"];
$scope.users.push({name: "A", roles: [{type: "a", enabled:true}]});
$scope.users.push({name: "B", roles: [{type: "b", enabled:true}]});
$scope.users.push({name: "C", roles: [{type: "b", enabled:true}, {type: "c", enabled:true}]});

$scope.findUserRole = function(userRoles, role){

  for(i in userRoles)
  {
    var userRole = userRoles[i];
    if ( userRole.type === role )
    {
      return userRole;
    }
  }

  return null;

}

$scope.addUserRole = function(roles, role){
  roles.push({type: role, enabled: true});
}

I dont manage to get the checkbox appear when adding a role

Do you have any idea ?

The plunkr : http://plnkr.co/edit/aIROCvAN2YztUdR4C3Pb?p=preview

Thanks.


Solution

  • ng-init is executed once. As the documentation indicates, you should almost never use ng-init.

    Just avoid it and get the user role in the ng-if:

    <li> {{role}}  
      <input ng-if="findUserRole(user.roles, role)" type="checkbox" ng-model="userRole.enabled">
      <input ng-if="!findUserRole(user.roles, role)" type="button" ng-click="addUserRole(user.roles, role)" value="add">
    </li>