2015-11-16 1 views
0

В приложении AngularJs я пытаюсь использовать константу для рендеринга нескольких вещей, таких как ДА или НЕТ, используя константу. Но не удалось его реализовать.AngularJS + Использование константы JavaScript + Невозможно просмотреть в UI

Отрывок: -

/* 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, имя: "Джон", возраст: 20, is_student: правда, наука: "нет"}

На UI - браузер Проверьте 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

Вы должны поместить их в контроллер $scope, чтобы он мог получить доступ к HTML.

Если это постоянное значение, которое вряд ли изменится, тогда я предпочту вам создать угловой constant, который является видом обслуживания.

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 d прямо внутри контроллера. В то время, связывая данные для просмотра, вы должны вызвать метод &, что этот метод выполнит операцию и вернет данные.

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; 
}; 
+0

@Rubyist могли бы вы посмотреть на обновленный ответ .. –

+0

PlusOne - Отлично One. Я пробую ваше предложение. – Rubyist

 Смежные вопросы

  • Нет связанных вопросов^_^