0

Problem Question -

I am trying to use ng-show and ng-hide but I don't know where I am making mistake.When my object is empty it is not hiding the div.

Can someone please guide me on this is much appreciated

//this is my view

<div class="main" ng-controller="myCtrl">
 <div ng-show="show">
      Show me as json object is not empty
 </div>
 <div ng-hide="show">
     hide me as my json object is empty
 </div>
</div>

//my controller

 myCtrl();

        function myCtrl() {
            Service.getMoney()
                .success(function (data) {
                    if(data !=null || data != 'undefined'){
                        $scope.data = data;
                        $scope.show= true;
                        console.log(cart);
                    }
                    else{
                       $scope.show= false;
                   }
                })
                .error(function (status, data) {
                    console.log(status);
                })
        };

Please guide me where I am making mistake. Also my json(data) is coming like this (Object {}) if it is empty

Update answer: It was nothing to do with ng-show and ng-hide. I have to just check my json object if (data.value) // Thanks to @shomz

GeekOnGadgets
  • 941
  • 3
  • 14
  • 47

1 Answers1

0

Well, if your response comes as an empty object, then if(data !=null || data != 'undefined') won't work - it will always be true.

In fact, that condition will ALWAYS be true, because no object can be a null and 'undefined' at the same time.

Your Angular part seems fine, but you need to fix your JS conditions. The simplest fix would be to modify your service to return false it there is no data.

See how it's always true:

alert({} != null || {} != 'undefined');
Shomz
  • 37,421
  • 4
  • 57
  • 85
  • what is the way to check for the empty object in angular? I tried different things but no luck so far. thanks – GeekOnGadgets Dec 12 '14 at 03:23
  • Nothing related to angular here, it's a plain js issue: http://stackoverflow.com/questions/4994201/is-object-empty?lq=1 – Shomz Dec 12 '14 at 03:25
  • The easist way would be to return false, or to check against something you know it's there after a successful call. Say, you know you'll have `data.json` in a successful call, then you simply check for it: `if (data.json) {...` – Shomz Dec 12 '14 at 03:26
  • There's no point in checking for null unless you're really returning null from the service when there's no data. If you really don't want to modify your service, use one of the functions from the link I gave you to check for an empty object. – Shomz Dec 12 '14 at 03:39
  • i have to check for null to hide the div. – GeekOnGadgets Dec 12 '14 at 03:43
  • Not for `null` unless your service returns `null`. – Shomz Dec 12 '14 at 03:44
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/66701/discussion-between-geekongadgets-and-shomz). – GeekOnGadgets Dec 12 '14 at 03:45