AngularJS watching an expression -
say have expression
$scope.showbutton = users.is_admin() && !document.is_provided;
and in same controller have button updates value of document.is_provided
:
<button ng-click="document.is_provided = true;">provide document</button>
the problem $scope.showbutton
should changed it's not changing.
updated: plnkr showing simplified issue: http://plnkr.co/edit/qk2jnhamqsrnxsajdyek?p=preview
i'd add on squiroid's answer , explain why works. i'll provide simple way understand, common problem me when started.
angular has called digest cycle. series of functions called successively make sure if variable two-way bound variable b (using ng-model example), stay in sync (that is, have same value). functions angular provides (or services, start $, $timeout etc), automatically start digest cycle
so let's have variable , you've bound $scope variable b, equal variable c. expect c bound too, right? because think when change c, b should change, , so, should change too. possible when start digest cycle. cycle variables need updated, , update them. however, changing value of c, never trigger digest cycle, , change never propagate a.
what when put variable in $watch (as $ suggests), forcefully start digest cycle. when change c, start cycle, tracks down needs update too, , that's why works.
in example, $scope.showbutton bound document.is_provided. you're using non-angular function change value of document.is_provided. means not trigger digest cycle, , means change never propagated $scope.showbutton. therefore, showbutton remains false.
and of course, example understand: http://jsbin.com/vojoso/edit?js,console,output
watch console. i've added logs understand. comment out $watch statement , see happens. try understanding , doing yourself, you'll it.
hope helped :)
Comments
Post a Comment