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

djs*_*ith 0 javascript angularjs

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

输入示例:

<div ng-controller="MyController">
  {{oops}} <!-- This name does not exist in my $scope -->
</div>
Run Code Online (Sandbox Code Playgroud)

期望的输出:

<div ng-controller="MyController">
    ERROR: No such name: "oops"
</div>
Run Code Online (Sandbox Code Playgroud)

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

Ben*_*esh 7

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

app.filter('undefined', function(){ 
    return function(input, message) {
        return angular.isDefined(input) ? input : message;
    };
});
Run Code Online (Sandbox Code Playgroud)

使用:

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

这应该够了吧.


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

HTML

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

在你的控制器中:

app.controller("MyController", function($scope) {
   $scope.isDefined = function(x) {
      return angular.isDefined(x);
   };
});
Run Code Online (Sandbox Code Playgroud)

编辑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.
  });
});
Run Code Online (Sandbox Code Playgroud)

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