Reputation: 3087
How can I instruct Angular to notify me any time my HTML references a name in my $scope
that does not exist?
Example input:
<div ng-controller="MyController">
{{oops}} <!-- This name does not exist in my $scope -->
</div>
Desired output:
<div ng-controller="MyController">
ERROR: No such name: "oops"
</div>
In Django, this can be achieved with the TEMPLATE_STRING_IF_INVALID
setting.
Upvotes: 0
Views: 1962
Reputation: 2847
it can be as simply what the function means. The return should determine if you show a message or any other logic.
app.filter('isDefined', function () {
return angular.isDefined;
});
Upvotes: 0
Reputation: 108491
EDIT: Doing it with a filter... (which will be global)
app.filter('undefined', function(){
return function(input, message) {
return angular.isDefined(input) ? input : message;
};
});
Use:
<div ng-controller="MyController">
{{oops | undefined:'ERROR: No such name: "oops"'}} <!-- This name does not exist in my $scope -->
</div>
That should do the trick.
This is the quick and easy way to do it...
HTML
<div ng-controller="MyController">
<span ng-show="isDefined(oops)">{{oops}}</span><span ng-hide="isDefined(oops)">ERROR: No such name: "oops"</span>
</div>
In your controller:
app.controller("MyController", function($scope) {
$scope.isDefined = function(x) {
return angular.isDefined(x);
};
});
EDIT 2: A truly "global" approach that does it all "automagically"... To do that you're looking at either rewriting Angular's ngBind directive, or creating your own binding directive and using it everywhere.
Here is Angular's ngBind directive, found on line 50 here:
var ngBindDirective = ngDirective(function(scope, element, attr) {
element.addClass('ng-binding').data('$binding', attr.ngBind);
scope.$watch(attr.ngBind, function ngBindWatchAction(value) {
element.text(value == undefined ? '' : value); //<-- this is the line.
});
});
As you can see, it just defaults to '' when the value isn't defined.
Upvotes: 7