I am trying to understand ng-if and scopes. As I am aware, ng-if creates a new child scope. Here is my issue:
View
<input ng-model="someValue1" />
<div ng-if="!someCondition">
<input ng-model="$parent.someValue2" />
</div>
Controller
$scope.someCondition = true;
if ($scope.someCondition) {
$scope.someValue2 = $scope.someValue1;
}
If someCondition is set to true, then someValue2 should be the same as someValue1.
My problem is that I can't access someValue2 in both situations (true or false). How could I achieve this?
AngularJS ng-if Directive 1 Definition and Usage. The ng-if directive removes the HTML element if the expression evaluates to false. ... 2 Syntax. Supported by all HTML elements. 3 Parameter Values. An expression that will completely remove the element if it returns false. If it returns true, a copy of the element will be inserted instead.
How to Use the Scope? When you make a controller in AngularJS, you pass the $scope object as an argument: When adding properties to the $scope object in the controller, the view (HTML) gets access to these properties. In the view, you do not use the prefix $scope, you just refer to a property name, like { {carname}}.
The element will be added to the DOM if all conditions are fulfilled. The following example demos how AngularJS evaluates an AND condition: If only one of the conditions is true, you can use *ngIf to display the element with the help of the OR (||) operator. The following code snippet demonstrates the use of the OR condition in ngIf.
When using HTML elements in the *ngif directive, angular will wrap that element in a <ng-template> tag with the provided condition. To learn more about ng-template, click here. In the Angular framework, <ng-template> is a pseudo element that will not be included in the final HTML output. Only the elements within the <ng-template> will be inserted.
Yes, ng-if
creates a new child scope
To watch a model property in an ng-if
, the rule-of-thumb is:
DO NOT USE THE SCOPE AS MODEL
e.g.
ng-if='showStuff' //here my scope is model **INCORRECT**
ng-if='someObject.showStuff' // ** CORRECT **
Use an object property in ng-model - then, even if ng-if
creates the new child scope, the parent scope will have the changes.
To see a working Plunker, look here : http://jsfiddle.net/Erk4V/4/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With