在AngularJs的应用程序中,我试图使用常量来渲染一些事情,比如使用常量渲染YES或NO。但无法实施。
代码段:-
/*constant.js文件*/
/*
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输出
{id:1,姓名:"John",年龄:20,is_student:true,奖学金:"no"}
在UI上-浏览器检查标高
<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>
您应该将这些常量放在控制器$scope
中,以便它可以在HTML上访问。
如果这是一个几乎不会改变的常数值,那么我更希望你创建一个角度constant
,这是一种服务。
常量
app.constant('myConstants', {
CONSTANT_TRUE : "True",
CONSTANT_FALSE : "False",
CONSTANT_YES : "Yes",
CONSTANT_NO : "No"
})
控制器
app.controller('myCtrl', function($scope, myConstants){
//other awesome code here
$scope.myConstants = myConstants; //binded to the scope to get access to constant on HTML.
})
编辑
如果您不想在$scope
中公开常量,那么我建议您直接在控制器中使用myConstants
。在绑定数据到视图时,您需要调用方法&该方法将执行一个操作并返回数据。
标记
<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>
控制
$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;
};