Reputation: 6542
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>
Upvotes: 0
Views: 42
Reputation: 136174
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;
};
Upvotes: 1