如何检查对象中的对象是否为空?

时间:2016-05-27 06:34:05

标签: arrays angularjs

我的angularjs控制器中有一些对象。

var app = angular.module("myApp", []);

app.controller("noteCtrl", function ($scope) {
    $scope.draft = {};
    $scope.notes = [];
    $scope.note = {};

$scope.submit = function() {
    $scope.notes.push($scope.note);
    $scope.note = {};
}; 

    $scope.save = function() {
        if ($scope.button == "Save") {
            $scope.draft = angular.copy($scope.note);
        } else {
            $scope.note = $scope.draft;
        }
    }; 

    $scope.cancel = function() {
        $scope.note = {};
    }
});

我需要检查草稿对象是否为空,并输出保存成功信息。

<span data-ng-hide="draft == {}" style="color:green">Your note has been saved.</span>

我也尝试过:

<span data-ng-hide="draft.length == -1" style="color:green">Your note has been saved.</span>

<span data-ng-hide="draft == ''" style="color:green">Your note has been saved.</span>

但他们都失败了。

3 个答案:

答案 0 :(得分:2)

在控制器中添加功能cxf-rt-frontend-jaxrs

isEmptyObject

或者您可以使用此功能:

var app = angular.module("myApp", []);

app.controller("noteCtrl", function ($scope) {

  $scope.draft = {};
  $scope.note = {};
  $scope.notes = [];

  $scope.save = function() {
    if ($scope.button == "Save") {
      $scope.draft = angular.copy($scope.note);
    } else {
      $scope.note = $scope.draft;
    }
  }; 

  $scope.cancel = function() {
    $scope.note = {};
  }

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

});

HTML:

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

答案 1 :(得分:1)

请初始化null而不是空对象

$scope.draft = null;

html应该是

<span data-ng-hide="!draft" style="color:green">Your note has been saved.</span>

答案 2 :(得分:0)

你可以在你的范围内内联条件。

HTML:

<span data-ng-hide="Object.keys(draft).length === 0" style="color:green">Your note has been saved.</span>