简体   繁体   中英

Is it possible to know if my AngularJS HTML references a non-existent $scope value?

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.

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.

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;
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM