Question

I've noticed that when binding to a property that doesn't exist in the current scope, you don't get a Javascript error. I believe in fact that Angular sets up a new property on the scope instead.

I used to use KnockoutJS, which did throw a JS error when the data-bind expression referred to an undefined property on the viewmodel.

Is there a way to configure AngularJS to do the same thing? I prefer this 'strict' validation approach, as having the JS error message helps in troubleshooting

Example HTML:

<div ng-app>
    <div ng-controller="ctrl">
        {{username1}}
    </div>
</div>

And Javascript:

function ctrl( $scope ) {
    $scope.username = 'user1';
}

The typo on the HTML means that the binding doesn't match. It would be great to get a JS error to tell me that...

Was it helpful?

Solution

You could potentially create a filter that checks for the property being undefined:

app.filter("throwUndefined", function ($exceptionHandler) {
        return function (input) {
            if (input === undefined) {
                $exceptionHandler(new Error("Property was undefined"),
                                  "throwUndefined filter");
            }
            return input;
        };
    });

Seems a bit of overhead but with HTML like this:

<div ng-app="myApp" ng-controller="myController">
    {{variable | throwUndefined}}
    {{variable1 | throwUndefined}}
</div>

The undefined variables will call the exception handler. There is not a way to see the property that triggered this or to see if it was because the property isn't defined or was set to the value undefined, but you could plumb the call stack to find it. It seems you want more trust between your view and the controller, though - i.e. I'd say have your controller check but if you do that you can always ensure a value is set.

Fiddle: http://jsfiddle.net/jeremylikness/BHjRg/

OTHER TIPS

This does not throw an exception because $scope.username1 == undefined. $scope is just a plain javascript object and so asking for a key that does not exist will always return undefined. {{undefined}} will interpolate to an empty string; thus, no exception. You would suffer the same fate if your HTML contained {{bacon}}. Hope that helps!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top