4

I tried using ng-click to update the variable used in ng-switch, but ng-switch doesn't seem to have picked up the change. See the example here: http://plnkr.co/edit/jx8DNlrJDuaUBKVwZQtQ

What am I doing wrong?

m59
  • 43,214
  • 14
  • 119
  • 136
extraeee
  • 3,096
  • 5
  • 27
  • 28

2 Answers2

9

You're running into scope inheritance issues. See: http://docs.angularjs.org/guide/scope

Fixed version: http://plnkr.co/edit/ENm5HBYno8yHblLlE8CA?p=preview

Jeff Hubbard
  • 9,822
  • 3
  • 30
  • 28
  • Interesting, so if I understand correctly, ng-switch creates a new scope and a new 'edit' variable which is changed in ng-click, but not the old 'edit' that ng-switch is watching on. But why does your solution fix it? Why doesn't it just create another 'x.edit'? – extraeee Dec 14 '13 at 20:44
  • 1
    Because of the way prototypal inheritance works. When you were setting the edit property, it was being attached to the current (i.e. ngSwitch-created) scope, and the parent scope (yours) didn't know about it. By putting a property in-between the edit variable and the scope (i.e. x.edit), you force it to look for the x first, which it finds on the correct scope, and then set the edit property. – Jeff Hubbard Dec 14 '13 at 20:58
0

You just weren't toggling. Try this.

<div ng-switch on="edit">
  <div ng-switch-when=true>
    <a ng-click="edit=!edit">Cancel {{edit}}</a>
  </div>
  <div ng-switch-when=false>
    <a ng-click="edit=!edit">Edit {{edit}}</a>
  </div>
</div>
Darryl
  • 1,451
  • 1
  • 12
  • 19
  • Did this not work for you? I tested it and it worked for me. Did I misunderstand your question? – Darryl Dec 17 '13 at 21:48