0

Function are over called with expressions in AngularJS

I want to get the label binded to the selectedType value in the option tag but nothing is shown in the view and in the console there are many calls

view.jsp

<select ng-if="RCDModel.id!=-1" class="form-control overloadDC"
        title="blablabla" disabled>
    <option value="{{RCDModel.selectedType}}"> 
      {{exprModelType(RCDModel.selectedType)}}
    </option>                                   
</select>

Controller.js

$scope.exprModelType = function(typeModel) {
    if (typeModel != undefined) {
        $scope.reunionType.forEach(function (type) {
            console.log("TYPE: "+type);
            if (type.id == typeModel) {
                console.log("TYPE ID: "+type.id);
                console.log("TYPE ID: "+typeModel);
                console.log("Libele: "+type.libelle);
                return type.libelle;
            }
        });
    }
    return "";
}

enter image description here

Community
  • 1
  • 1
mtnp
  • 314
  • 7
  • 24
  • Do you want to show selected model from reunionType array or for all the values present inside reunionType array ? – Jasdeep Singh Mar 13 '20 at 17:46
  • Just the selected model. reunionType array is key/value of id/label and my model contains only ids. So I have to get the label linked to the id model. I use AngularJS 1.3 – mtnp Mar 13 '20 at 17:48

1 Answers1

1

The return statement inside a forEach block does not return values to the parent function.

Instead use array.find:

$scope.exprModelType = function(typeModel) {
    if (typeModel != undefined) {
        var idMatch = $scope.reunionType.find( _ => _.id == typeModel.id );
        console.log("TYPE: "+idMatch); 
        console.log("TYPE ID: "+idMatch.id);
        console.log("TYPE ID: "+idModel);
        console.log("Libele: "+idMatch.libelle);
        return idMatch ? idMatch.libelle : "";
    }
    return "";
}

For more information, see

georgeawg
  • 48,608
  • 13
  • 72
  • 95
  • IE doesn't support array.find but I used this solution https://stackoverflow.com/a/52412322/5240905 and it works perfectly. Thank you ! – mtnp Mar 16 '20 at 10:11