AngularJS ng-bind с функцией
Я хочу показать формат таблицы для раздела "Вложения". У меня есть результаты поиска и результатов. Оба имеют общий столбец attachmentTypeId
. Я хочу показать описание категории привязки на основе идентификатора. В ng-bind
я попытался попытаться, он не сработал.
Я использую функцию в ng-bind
, надеюсь, что подход неверен, ожидайте альтернативы для подхода.
attachmentLookup
содержит attachmentDesc
, attachmentTypeId
$scope.attachmentLookup = [{
"attachmentDesc": "Category One",
"attachmentTypeId": "1"
}, {
"attachmentDesc": "Category Two",
"attachmentTypeId": "2"
}, {
"attachmentDesc": "Category Three",
"attachmentTypeId": "3"
}, {
"attachmentDesc": "Category Four",
"attachmentTypeId": "4"
}, {
"attachmentDesc": "Category Five",
"attachmentTypeId": "5"
}];
И данные attachmentDetails
из базы данных как,
$scope.attachmentDetails = [{
"attachmentId": "001",
"fileName": "File Name 001",
"attachmentTypeId": "1"
}, {
"attachmentId": "003",
"fileName": "File Name 003",
"attachmentTypeId": "2"
}, {
"attachmentId": "005",
"fileName": "File Name 005",
"attachmentTypeId": "3"
}, {
"attachmentId": "007",
"fileName": "File Name 007",
"attachmentTypeId": "1"
}, {
"attachmentId": "009",
"fileName": "File Name 009",
"attachmentTypeId": "2"
}, {
"attachmentId": "011",
"fileName": "File Name 011",
"attachmentTypeId": "3"
}];
Код HTML как,
<table>
<thead>
<tr>
<th>File Name</th>
<th>|</th>
<th>Category</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="attachment in attachmentDetails">
<td> <span ng-bind="attachment.fileName"></span>
</td>
<td>|</td>
<td> <span ng-bind="getCatgoryName(attachment.attachmentTypeId)"></span>
</td>
</tr>
</tbody>
</table>
И код getCatgoryName
от контроллера:
$scope.getCatgoryName = function (attachmentTypeId) {
angular.forEach($scope.attachmentLookup, function (attachemnt) {
if (attachemnt.attachmentTypeId === attachmentTypeId)
return attachemnt.attachmentDesc;
});
};
Пример Plunker: http://plnkr.co/edit/dZy5gW4q9CxWF2NszXYc
Ответы
Ответ 1
Скобки грязные, поэтому функция будет вызываться для каждого $digest
.
Этот ng-bind
является директивой, он будет использовать наблюдателя на том, что передается на ng-bind
.
Следовательно, ng-bind
будет применяться только тогда, когда переданная переменная или значение действительно изменится.
С помощью функции вы не передаете переменную, поэтому она не будет срабатывать для каждого $digest
.
Поэтому лучше использовать скобки с вызовом функции.
Я обновил плункер здесь: http://plnkr.co/edit/LHC2IZ0Qk9LOOYsjrjaf?p=preview
Я изменил HTML здесь:
<tr ng-repeat="a in attachmentDetails">
<td> <span>{{a.fileName}}</span></td>
<td>|</td>
<td> {{ getCatgoryName(a.attachmentTypeId) }}</td>
</tr>
Функция также была изменена:
$scope.getCatgoryName = function(attachmentTypeId) {
var desc = "";
angular.forEach($scope.attachmentLookup, function(attachemnt) {
if (parseInt(attachemnt.attachmentTypeId) == attachmentTypeId)
desc = attachemnt.attachmentDesc;
});
return desc;
};
Ответ 2
Другой способ сделать то же самое, как показано ниже:
<tr ng-repeat="delivery in deliveries">
<td>{{delivery.pickup}}</td>
<td>{{delivery.destination}}</td>
<td>{{getVehicleDescription(delivery) || (delivery.isVehicleDescription ? delivery.modelType : delivery.vehicleType)}}</td></tr>
Функция контроллера также была изменена таким образом:
$scope.getVehicleDescription = function(delivery){
$scope.roads.map(function(road){
if(road.modelTypeID == delivery.vehicleType && !delivery.isVehicleDescription){
delivery.modelType = road.modelType;
delivery.isVehicleDescription = true;
}
})
};