是否有可能知道我的 AngularJS HTML 是否引用不存在的$scope值



如何指示 Angular 在我的 HTML 引用$scope中不存在的名称时通知我?

示例输入:

<div ng-controller="MyController">
  {{oops}} <!-- This name does not exist in my $scope -->
</div>

期望输出:

<div ng-controller="MyController">
    ERROR: No such name: "oops"
</div>

在 Django 中,这可以通过TEMPLATE_STRING_IF_INVALID设置来实现。

编辑:使用过滤器执行此操作...(这将是全球性的)

app.filter('undefined', function(){ 
    return function(input, message) {
        return angular.isDefined(input) ? input : message;
    };
});

用:

<div ng-controller="MyController">
  {{oops | undefined:'ERROR: No such name: "oops"'}} <!-- This name does not exist in my $scope -->
</div>

这应该可以解决问题。


这是快速简便的方法...

.HTML

<div ng-controller="MyController">
    <span ng-show="isDefined(oops)">{{oops}}</span><span ng-hide="isDefined(oops)">ERROR: No such name: "oops"</span>
</div>

在控制器中:

app.controller("MyController", function($scope) {
   $scope.isDefined = function(x) {
      return angular.isDefined(x);
   };
});

编辑2:一种真正的"全球"方法,可以"自动"地完成所有操作......为此,您需要重写Angular的ngBind指令,或者创建自己的绑定指令并在任何地方使用它。

这是Angular的ngBind指令,位于第50行:

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

如您所见,当未定义值时,它只是默认为"。

它可以

是函数的含义。返回应确定是否显示消息或任何其他逻辑。

  app.filter('isDefined', function () {
    return angular.isDefined;
  });

最新更新