Osama Salama Osama Salama - 5 months ago 10
Javascript Question

How to hide an element from DOM using ngif with angular.js and angularmaterial?

I'm using angular.js 1.5, and angular material in the frontend to load the DOM with objects from the Database.
In one of the repeaters, I need to check if an object is already included inside another in-scope javascript array. I tried to do it with

Array.indexOf()
, with
Array.forEach
, with a standard for loop looping over each element but it's not happening the way I need it. I must be doing something silly that's preventing the logic to run normally, Ideally a method should return false if the current object exists in the array, or true if it doesn't.

the use case is that the user needs to add item(s) ObjA to a list (ObjX.Objs) from another list (Objs)

my front end html code :

//here there's an object that contains an array of objects
<div ng-controller="myFirstController" ng-init="findOne()">
<md-list-item ng-repeat="ObjA in ObjX.Objs" >
</md-list-item>
<div ng-controller="mySecondcontroller" ng-init="find()">
<md-list-item ng-repeat="ObjA in Objs" ng-if="ObjAExists(ObjA, ObjX.Objs)">
</md-list-item>
</div>
</div>


Controller method :

$scope.ObjAExists = function(ObjA, list){
for(var m = 0; m<list.length; m++){
if(list[m] === ObjA){
return false;
}
else return true;
}
}


I also tried to match object Id's no difference

$scope.ObjAExists = function(ObjA, list){
for(var m = 0; m<list.length; m++){
if(list[m]._id == ObjA._id){
return false;
}
else return true;
}
}


Filter skills plunk
There's a plunk I wrote representing the same problem

Answer

You're comparing ObjA only with first element in list. You should pull return true; out of for loop. It will be:

$scope.ObjAExists = function(ObjA, list){
 for(var m = 0; m<list.length; m++){
     if(list[m]._id == ObjA._id){
         return false;
     }
 }
 return true;
}

* And the name of the method should certainly be ..NotExists


Here's example answering your question from the comments. Pay attention:

  • we can't compare by reference because friend.skills are not the same objects we have in general skills list. That's why compared by name property.
  • it would be cleaner to use filter instead of ng-if for filtering "used" skills list