Skip to content
This repository was archived by the owner on Apr 12, 2024. It is now read-only.

Fixing bug where ngIf adds children repeatedly if condition goes from tr... #4894

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 13 additions & 5 deletions src/ng/directive/ngIf.js
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@
}

/*
The transition styles can also be placed on the CSS base class above
The transition styles can also be placed on the CSS base class above
*/
.animate-if.ng-enter, .animate-if.ng-leave {
-webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
Expand Down Expand Up @@ -89,10 +89,10 @@ var ngIfDirective = ['$animate', function($animate) {
compile: function (element, attr, transclude) {
return function ($scope, $element, $attr) {
var block, childScope;
var previousValue = false;
$scope.$watch($attr.ngIf, function ngIfWatchAction(value) {

if (toBoolean(value)) {

function addChildren() {
childScope = $scope.$new();
transclude(childScope, function (clone) {
block = {
Expand All @@ -101,9 +101,9 @@ var ngIfDirective = ['$animate', function($animate) {
};
$animate.enter(clone, $element.parent(), $element);
});
}

} else {

function removeChildren() {
if (childScope) {
childScope.$destroy();
childScope = null;
Expand All @@ -114,6 +114,14 @@ var ngIfDirective = ['$animate', function($animate) {
block = null;
}
}

if (toBoolean(value) && !previousValue) {
previousValue = true;
addChildren();
} else if (!toBoolean(value)) {
previousValue = false;
removeChildren();
}
});
};
}
Expand Down
6 changes: 6 additions & 0 deletions test/ng/directive/ngIfSpec.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,12 @@ describe('ngIf', function () {
expect(element.children().length).toBe(1);
});

it('should not add the element twice if the condition goes from true to true', function () {
makeIf('true');
makeIf('true');
expect(element.children().length).toBe(1);
});

it('should create then remove the element if condition changes', function () {
$scope.hello = true;
makeIf('hello');
Expand Down