Javascript 如何在 AngularJS 视图中检查空对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32586180/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 10:39:58  来源:igfitidea点击:

How to check for an empty object in an AngularJS view

javascriptangularjs

提问by brabertaser19

In the controller's scope I have something like:

在控制器的范围内,我有类似的东西:

$scope.card = {};

In the view I must check if my object is still an empty literal, {}, or if it contains some data in some fields.

在视图中,我必须检查我的对象是否仍然是空文字{},或者它是否在某些字段中包含一些数据。

I tried this:

我试过这个:

ng-show="angular.equals({}, card)"

and

ng-show="!angular.equals({}, card)"

but it didn't work.

但它没有用。

Are there any better ways? How do you check if an object is empty or if it contains some fields?

有没有更好的方法?如何检查对象是否为空或是否包含某些字段?

回答by Md Hasan Ibrahim

You can use: Object.keys(card).length === 0

您可以使用: Object.keys(card).length === 0

But make sure you use it from a method of the controller as the Objectis not available in the view, like:

但是请确保您从控制器的方法中使用它,因为Object视图中不可用,例如:

$scope.isObjectEmpty = function(card){
   return Object.keys(card).length === 0;
}

Then you can call the function from the view:

然后您可以从视图中调用该函数:

ng-show="!isObjectEmpty(card)"

回答by Wallace Maxters

Use jsonfilter and compare with '{}'string.

使用json过滤器并与'{}'字符串进行比较。

<div>
    My object is {{ (myObject | json) == '{}' ? 'Empty' : 'Not Empty' }}
</div>

ng-showexample:

ng-show例子:

<div ng-show="(myObject | json) != '{}'"></div>

回答by Yogesh Kate

Try this:

尝试这个:

angular.equals({}, $scope.card)

回答by Jahongir Rahmonov

Create a function that checks whether the object is empty:

创建一个函数来检查对象是否为空:

$scope.isEmpty = function(obj) {
  for(var prop in obj) {
      if(obj.hasOwnProperty(prop))
          return false;
  }
  return true;
};

Then, you can check like so in your html:

然后,您可以在 html 中像这样检查:

ng-show="!isEmpty(card)"

回答by Moncef Hassein-bey

http://plnkr.co/edit/u3xZFRKYCUh4D6hGzERw?p=preview

http://plnkr.co/edit/u3xZFRKYCUh4D6hGzERw?p=preview

Because angular is not available from the scope, you can pass it to your controller scope.

因为 angular 在范围内不可用,您可以将其传递给您的控制器范围。

$scope.angular = angular;

回答by Ramesh Rajendran

please try this way with filter

请用过滤器试试这种方式

angular.module('myApp')
    .filter('isEmpty', function () {
        var bar;
        return function (obj) {
            for (bar in obj) {
                if (obj.hasOwnProperty(bar)) {
                    return false;
                }
            }
            return true;
        };
    });

usage:

用法:

 <p ng-hide="items | isEmpty">Some Content</p>

Via from : Checking if object is empty, works with ng-show but not from controller?

通过来自:检查对象是否为空,可与 ng-show 一起使用,但不能从控制器中使用?

回答by Ramesh Rajendran

This will do the object empty checking:

这将执行对象空检查:

<div ng-if="isEmpty(card)">Object Empty!</div>


$scope.isEmpty = function(obj){
  return Object.keys(obj).length == 0;
}

回答by pherris

You should not initialize your variable to an empty object, but let it be undefinedor nulluntil the conditions exist where it should have a non-null/undefinedvalue:

您不应该将变量初始化为空对象,而是让它成为undefinednull直到条件存在时它应该具有非null/undefined值:

$scope.card;

if (someCondition = true) {
    $scope.card = {};
}

Then your template:

然后你的模板:

ng-show="card"

回答by Pravin P Patil

You can use plain javascript Object class to achieve it, Object class has keys function which takes 1 argument as input as follows,

您可以使用普通的 javascript Object 类来实现它,Object 类具有以 1 个参数作为输入的键函数,如下所示,

Object.keys(obj).length === 0

Object.keys(obj).length === 0

You can achieve it in 3 ways, 1) Current controller scope 2) Filter 3) $rootScope

您可以通过 3 种方式实现它,1) 当前控制器作用域 2) 过滤器 3) $rootScope

1) First way is current controller scope,

1)第一种方式是当前控制器范围,

$scope.isObjEmpty = function(obj){ return Object.keys(obj).length === 0; }

$scope.isObjEmpty = function(obj){ return Object.keys(obj).length === 0; }

Then you can call the function from the view:

然后您可以从视图中调用该函数:

ng-show="!isObjEmpty(obj)" if you want to show and hide dom dynamically & ng-if="!isObjEmpty(obj)" if you want to remove or add dom dynamically.

ng-show="!isObjEmpty(obj)" 如果你想动态地显示和隐藏 dom & ng-if="!isObjEmpty(obj)" 如果你想动态删除或添加 dom。

2) The second way is a custom filter. Following code should work for the object & Array,

2)第二种方式是自定义过滤器。以下代码应该适用于对象和数组,

angular.module('angularApp')
    .filter('isEmpty', [function () {
        return function (obj) {
            if (obj == undefined || obj == null || obj == '')
                return true;
            if (angular.isObject(obj))
                return Object.keys(obj).length != 0;

            for (var key in obj) {
                if (obj.hasOwnProperty(key)) {
                    return false;
                }
            }
            return true;
        };
    }]);

    <div ng-hide="items | isEmpty"> Your content's goes here </div>

3) The third way is $rootScope, create a plain javascript function and add it in $rootScope server it will accessible default in all scopes and UI.

3) 第三种方式是 $rootScope,创建一个普通的 javascript 函数并将其添加到 $rootScope 服务器中,它将在所有范围和 UI 中默认访问。

function isObjEmpty (obj){ return Object.keys(obj).length === 0; }

$rootScope.isObjEmpty = isObjEmpty ;

function isObjEmpty (obj){ return Object.keys(obj).length === 0; }

$rootScope.isObjEmpty = isObjEmpty ;

回答by William Hou

A good and effective way is to use a "json pipe"like the following in your HTML file:

一个好的和有效的方法是在 HTML 文件中使用如下所示的“json 管道”

   <pre>{{ yourObject | json }}</pre>

which allows you to see clearly if the object is empty or not.

这使您可以清楚地看到对象是否为空。

I tried quite a few ways that are showed here, but none of them worked.

我尝试了很多这里展示的方法,但都没有奏效。