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

Detecting UNINITIALIZED_VALUE in $onChanges lifecycle hook #14917

@jkjustjoshing

Description

@jkjustjoshing

With a scope watcher, you can detect if it is the first time the watcher is running by checking if the new and old values are the same:

$scope.$watch('expr', function (newValue, oldValue) {
    if (newValue === oldValue) {
        // first time running
    }
});

However, with the Angular 1.5 $onChanges lifecycle hook, the placeholder object UNINITIALIZED_VALUE is the previousValue. However, there is no easy way to check for that. You can do it by checking the constructor's name:

ExampleController.prototype.$onChanges = function (changes) {
    if (changes.expr.previousValue.constructor.name === 'UNINITIALIZED_VALUE') {
        // first time running
    }
};

but that seems like a bit of a hack.

The best solution I can think of is having the UNINITIALIZED_VALUE object should be stored as a constant (read-only) somewhere (eg angular.UNINITIALIZED_VALUE) to compare against, though there are probably other solutions as well.

Thanks!!

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions