1

Angular Scoping With ng-if

 2 years ago
source link: https://twilblog.github.io/angular/javascript/2017/01/03/angular-scope.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Angular Scoping With ng-if

Posted on Jan 3, 2017

shaun avatar broken :(

Shaun Donnelly

Background

When using Angular 1.x, you might have a simple form that looks like this:

<input type="text" ng-model="someInput" />
<input type="text" ng-model="someOtherInput" ng-if="someConditionToCheck" />
<!--  Note the use of 'ng-if' on 'someOtherInput'. -->

<button ng-click="save()">Save</button>
function save() {
  console.log($scope.someInput, $scope.someOtherInput);
}

However, if you ran this code and clicked ‘Save’, $scope.someOtherInput would be undefined.

WTF is going on?

The issue is that ng-if creates its own scope, so someOtherInput isn’t defined on your usual controller scope.

Workaround

Fortunately the workaround is simple. Just use the controllerAs syntax, which is generally useful for various other reasons.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK