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
'programing' 카테고리의 다른 글
ESNext란? (0) | 2023.10.02 |
---|---|
멀티 테넌시(Multi-tenancy): Spring Data JPA로 여러 데이터 소스 관리 (0) | 2023.10.02 |
Mobile Web HTML5 Framework 선택하기 (0) | 2023.10.02 |
"안드로이드:백업 허용"이란 무엇입니까? (0) | 2023.10.02 |
jQuery가 선택한 옵션 값을 가져옵니다(텍스트가 아니라 'value' 속성). (0) | 2023.10.02 |