programing

Test if an object is an empty object in a AngularJS template

testmans 2023. 10. 2. 11:15
반응형

Test if an object is an empty object in a AngularJS template

컨트롤러에 가끔 비어 있을 수 있는 간단한 개체가 있습니다({}).

app.controller('TestController', function() {
  var vm = this;

  vm.testObject = {};
});

I want to hide or show some DOM-elements in the corresponding template when the object is empty or not.

저는 단순하게 하려고 했습니다.<div ng-if="vm.testObject">그러나 언제vm.testObject === {}고려됩니다.true에서ng-if.

<div ng-controller="TestController as vm">
  <div ng-if="vm.testObject">
    Test Object is not empty
  </div>
  <div ng-if="!vm.testObject">
    Test Object is empty
  </div>
</div>

Is there a simple way to check for an empty object in the template? Preferably without adding new variables to the scope.

Here is a working Plunker: http://plnkr.co/edit/Qed2MKmuedcktGGqUNi0?p=preview

You should use an AngularJs filter:

Javascript:

app.filter('isEmpty', [function() {
  return function(object) {
    return angular.equals({}, object);
  }
}])

Html template:

<div ng-if="!(vm.testObject | isEmpty)">
  Test Object is not empty
</div>
<div ng-if="vm.testObject | isEmpty">
  Test Object is empty
</div>

Updated plunkr: http://plnkr.co/edit/J6H8VzUKnsNv1vSsRLfB?p=preview

동일성 검사를 로 이동해도 괜찮습니까?ng-if?

<div ng-controller="TestController as vm">
  <div ng-if="!equals({}, vm.testObject)">
    Test Object is not empty
  </div>
  <div ng-if="equals({}, vm.testObject)">
    Test Object is empty
  </div>
</div>

Otherwise, provide a helper on the scope

app.controller('TestController', function() {
  var vm = this;

  vm.testObject = {};

  vm.empty = function() {
      return vm.testObject === {};
  };
});

then

<div ng-controller="TestController as vm">
  <div ng-if="!vm.empty()">
    Test Object is not empty
  </div>
  <div ng-if="vm.empty()">
    Test Object is empty
  </div>
</div>

This is an old thread but I find easier to check if the Object has keys.

<div ng-controller="TestController as vm">
  <div ng-if="Object.keys(vm.testObject).length">
    Test Object is not empty
  </div>
  <div ng-if="!Object.keys(vm.testObject).length">
    Test Object is empty
  </div>
</div>

It's simple and readable.

This will work. check the Length

<div ng-if="!!vm.testObject && vm.testObject.length > 0">
  Test Object is not empty
</div>

기본 제공 AngularJS를 사용하여 개체를 JSON 문자열로 변환할 수 있습니다.json필터링 및 비교는 다음과 같습니다.

<div ng-if="vm.testObject | json) != '{}'">
    Test Object is not empty
</div>

ReferenceURL : https://stackoverflow.com/questions/30366927/test-if-an-object-is-an-empty-object-in-a-angularjs-template

반응형