繁体   English   中英

如何检查Angular JS中是否存在对象?

[英]How to check if an object exist or not in angular js?

有没有办法知道对象在HTML中是否存在。 我有一个这样的对象。

$scope.object = {name : 'usman', profession : 'developer'}

现在我想在HTML中知道对象是否存在,或者对象仅包含这样的文本。

$scope.object = "Usman";

现在有我的条件。

    <div ng-if="object">
    <p>Object exist and have attributes</p>
    </div>

    <div ng-if="object">
    <p>object contain only string no attributes exist</p>
   </div>

我想写一个这样的合并条件-如果对象没有属性并且仅包含字符串,则显示div。

这里是 。

 <div ng-show="!objecthasnoattributes and objectOnlyContainsString">
<p>show this </p>
    </div>

现在我该怎么做?

您可以编写如下。

<div ng-if="object !== undefined"> </div>

要检查var的类型是OBJECT还是STRING ...,您可以按照以下步骤进行操作。

    $scope.object = {
        name: 'usman',
        profession: 'developer'
    };

    $scope.myString = "Usman";

    $scope.isString = function(val) {
        return typeof val === 'string';
    }
    $scope.isObject = function(val) {
        return typeof val === 'object';
    }

然后检查以下类型。

    <div ng-if="object !== undefined && isObject(object)">
        <p>Object Value </p>
    </div>
    <div ng-if="myString !== undefined && isString(myString)">
        <p>String value</p>
    </div>

询问更多查询

谢谢

使用单个方法可以更简短:

HTML:

<div ng-if="isObject()">
  <p>Object exist and have attributes</p>
</div>

<div ng-if="!isObject()">
  <p>object contain only string no attributes exist</p>
</div>

控制器:

$scope.isObject = function() {
  return typeof($scope.object) === 'object';
}

更新:

如果您只想显示字符串,

$scope.isString = function() {
  return typeof($scope.object) === 'string';
}

然后,您只需要一个html:

<div ng-if="isString()">
  <p>Show this</p>
</div>

这是一个改变的小家伙

您可以通过很多简单的方法。

$scope.object = {name : 'usman', profession : 'developer'};

$scope.getBType = function(test){
  return( typeof test);
}

<div ng-if="getBType(object)=='object' && getBType(object.name)=='string'">
<p> Show this</p>
</div>

如果您确定输入object将仅是以下类型。

$scope.object = {name : 'usman', profession : 'developer'};

$scope.object = "Usman";

您可以简单地使用:

<div ng-if="object && object.name">
    <p>Object exist and have attributes</p>
</div>

<div ng-if="object && !object.name">
    <p>object contain only string no attributes exist</p>
</div>

仅当对象存在并且具有名称属性时,条件#1才会被满足。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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