是否可以知道我的AngularJS HTML是否引用了不存在的$ scope值?

时间:2012-11-29 18:22:28

标签: javascript angularjs

如何指示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设置来实现。

2 个答案:

答案 0 :(得分:7)

编辑:使用过滤器...(这将是全局的)

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

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

答案 1 :(得分:0)

它可以简单地说明函数的含义。返回应确定您是否显示消息或任何其他逻辑。

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