Search code examples
javascriptangularjsangularjs-select

want to get label but nothing is shown in the view


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


Solution

  • 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