Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS: ng-if not working in combination with ng-click?

Given this test case using AngularJS 1.2 rc3: http://plnkr.co/edit/MX6otx (repeated below)

1.

<li ng-init="toggle1 = false">     ng-if toggle1: {{ toggle1 }}     <p>         <button ng-if="!toggle1" ng-click="toggle1 = true">Turn On</button>         <button ng-if="toggle1" ng-click="toggle1 = false">Turn Off</button>         does not work </li> 

2.

<li ng-init="obj={toggle2:false}">     ng-if obj.toggle2: {{ obj.toggle2 }}     <p>         <button ng-if="!obj.toggle2" ng-click="obj.toggle2 = true">Turn On</button>         <button ng-if="obj.toggle2" ng-click="obj.toggle2 = false">Turn Off</button>         then why does this work? </li> 

Questions:

  1. Why does 1 not work?
  2. Should 1 work?
  3. Why does 2 work?
  4. Should 2 work?
  5. Can I rely 2 to work in future updates of AngularJS?
like image 766
Blaise Avatar asked Nov 06 '13 12:11

Blaise


People also ask

Can we use NGIF and Ng show together?

ng-if is better in this regard. Using it in place of ng-show will prevent the heavy content from being rendered in the first place if the expression is false. However, its strength is also its weakness, because if the user hides the chart and then shows it again, the content is rendered from scratch each time.

Can we use NG-click and Onclick together?

For a single btn, it's ok to use ng-click or onclick in the ng-app . There is no difference between the two functions. For effective team work, you,d better to have an account with each other. In Angular apps, ng-click is recommended.

Can we call two functions on Ng-click?

When an HTML is clicked, the ng-click directive tells the AngularJS script what to do. In this article, we will learn how to get many/multiple functions to the ng-click directive passed, in just one click. The key is to add a semi-colon (;) or a comma (,). All the functions must be separated by a (;) or a (, ).

Which directive in AngularJS will be executed when the element is being clicked?

The ng-click directive defines AngularJS code that will be executed when the element is being clicked.


Video Answer


1 Answers

  1. Why does 1 not work?: Because an ngIf defines its own scope, which prototypically inherits from its parent scope (just like ngRepeat). So, when you change the value of a field inside an ngIf, you change it in the ngIf scope, and not in its parent scope.
  2. Should 1 work?: No
  3. Why does 2 work?: Because in that case you modify the content of an object which is referenced by the ngId scope, through inheritance.
  4. Should 2 work?: Yes
  5. Can I rely 2 to work in future updates of AngularJS?: Why shouldn't you?

This scope inheritance mechanism is explained very well in https://github.com/angular/angular.js/wiki/Understanding-Scopes

like image 76
JB Nizet Avatar answered Oct 15 '22 00:10

JB Nizet