سؤال

I need to show a word that is attributed to a number, in AngularJS. Through the controller I send to the view a variable $game.complexity, and complexity can be a number from 1 to 4. I want to take that number and show it as a word:

1 ---> easy

2 --->medium

what I initially thought was that maybe it would work with a cutstom filter:

var filtersModule = angular.module("ttmatchApp.Filters", [])

filtersModule.filter("complexityFilter", function(){
    return function(value){
        switch(value)
        {
            case 1: 
                return "easy"
                break;
            case 2:
                return "medium"
                break;
            case 3:
                return "hard"
                break;
            case 4:
                return "very hard"
                break;  

        }

    }
})

and call it like this:

<p>{{game.complexity | complexityFilter:game.complexity}} complexity</p></div>

i also tried it like this:

<p>{{game.complexity | complexityFilter}} complexity</p></div>

I define $scope.game within a controller, and i give it the necessary data through a json file. Other scope elements such as game.name work well, and show.

the filtersModule is also linked to the main module.

Do i have to introduce the filter to the controller as well?

Am i using the wrong method?

هل كانت مفيدة؟

المحلول

Once game.complexity is evaluated in the expression, it is outputted as a string. That means that your switch case should be on strings and not integers - "1" instead of 1, etc..

Edit: I was wrong, the expression is evaluated into a string, but the filter is still within that expression, so it receives game.complexity still as a number. The problem was what you solved in the comments.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top