Daniel Congrove
Daniel Congrove

Reputation: 3669

How to distinguish between null and '0' in Angular.js?

Is there a way to determine whether a value saved using the ng-model is simply null or if a 0 was typed, in Angular.JS?

Basically, I am trying to use resolve in my route to send the user back to #/page-1, if they try to go to #/page-2 and the vm.data.foo was not completed. Like in the case of a browser page refresh, which resets the temporary data.

The problem I have run into though, is that if the user types in a "0", it is being treated the same as a null value by Angular.JS. Is there anyway to make a distinction between the two using an if statement?

In my #/page-1 view:

<input type="number" ng-model="vm.Data.foo" />

My Route for #/page-2:

        $routeProvider.when("/page-2", {
            controller: "page2Controller",
            controllerAs: "vm",
            templateUrl: "/content/templates/page2View.html",
            resolve: {
                validate: function ($location, Data) {
                    // if Data.foo was not entered, send back to page-1
                    if (!Data.foo && Data.foo != 0) {
                        $location.path('/page-1');
                    }
                }
            }
        });

This was one of my attempts, but it does not work. On a browser refresh, it does not redirect back to page-1 when Data.foo is null, because it is seen the same as 0.

Any ideas for a work around?


Solution (thanks to Chet's answer):

    $routeProvider.when("/page-2", {
        controller: "page2Controller",
        controllerAs: "vm",
        templateUrl: "/content/templates/page2View.html",
        resolve: {
            validate: function ($location, Data) {
                // if Data.foo was not entered, send back to page-1
                if (Data.foo === '') {
                    $location.path('/page-1');
                }
            }
        }
    });

Upvotes: 1

Views: 3857

Answers (2)

ikken
ikken

Reputation: 563

Use simply :

if(Data.foo == null){}

In javascript, null, 0 and empty strings are processed as false when used in if statement as a statement

Upvotes: 2

Chet
Chet

Reputation: 3729

It's not that it is treating null as 0, it is treating both 0 and null as false. !(null) == true as is !(0) == true. You want something more like:

if (Data.foo === null) {

Upvotes: 2

Related Questions