0

In AngularJs app, I am trying to use constant for rendering few thing like YES or NO using Constant. But unable to implement it.

Snippet:-

/* constant.js File*/

/*
    Constant For Boolean
*/
var CONSTANT_TRUE  = "True"
var CONSTANT_FALSE = "False"
var CONSTANT_YES   = "Yes"
var CONSTANT_NO    = "No"

AngularJs Snippet:-

<table style="width:100%">
  <tr>
    <th>Name</th>
    <th>Age</th> 
    <th>Student</th>
    <th>Scholarship</th>
  </tr>
  <tr>
    <td>{{student.name}}</td>
    <td>{{student.age}}</td>
    <td>{{student.is_student == true ? CONSTANT_YES : CONSTANT_NO}}</td>
    <td>{{student.scholarship == "yes" ? CONSTANT_YES : CONSTANT_NO}}</td>
  </tr>
</table>

JSON Output

{ id: 1, name: "John", age: 20, is_student: true, scholarship: "no" }

On UI - Browser Inspect Eleement

<table style="width:100%">
  <tr>
    <th>Name</th>
    <th>Age</th> 
    <th>Student</th>
    <th>Scholarship</th>
  </tr>
  <tr>
    <td>John</td>
    <td>20</td>
    <td></td>
    <td></td>
  </tr>
</table>

1 Answer 1

1

You should place those constant in controller $scope so that it can get accessible on HTML.

If this are the constant value which are hardly going to change, then I will prefer you create an angular constant which is kind of service.

Constant

app.constant('myConstants', {
    CONSTANT_TRUE : "True",
    CONSTANT_FALSE : "False",
    CONSTANT_YES : "Yes",
    CONSTANT_NO : "No"
})

Controller

app.controller('myCtrl', function($scope, myConstants){
    //other awesome code here
    $scope.myConstants = myConstants; //binded to the scope to get access to constant on HTML.

})

Edit

If you don't wanted to expose constant inside the $scope then I'd suggest you to use myConstants directly inside the controller. At that time while binding data to view you need to call the method & that method will perform an operation and it will return data.

Markup

<table style="width:100%">
  <tr>
    <th>Name</th>
    <th>Age</th> 
    <th>Student</th>
    <th>Scholarship</th>
  </tr>
  <tr>
    <td>{{student.name}}</td>
    <td>{{student.age}}</td>
    <td>{{isStudent(student)}}</td>
    <td>{{isScholarship(student)}}</td>
  </tr>
</table>

Controlle

$scope.isStudent = function (){
    return student.is_student ? myConstants.CONSTANT_YES : myConstants.CONSTANT_NO;
};

$scope.isStudent = function (){
    return student.scholarship == "yes" ? myConstants.CONSTANT_YES : myConstants.CONSTANT_NO;
};
Sign up to request clarification or add additional context in comments.

1 Comment

PlusOne - Excellent One. I am trying your suggestion.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.