我是AngularJS的新手。
我想从html调用一个函数。
<td>
{{getComponentSubtype(component.ID)}}
</td>
但是,该函数调用webapi并等待回调。如何将数据显示在html中?
function getComponentSubtype(componentId) {
apiService.get('/api/components/' + componentId + '/componentSubtype', config,
getComponentSubtypeCompleted,
getComponentSubtypeFailed);
}
function getComponentSubtypeCompleted(result) {
$scope.ComponentSubtype = result.data;
//////I WANT TO RETURN $scope.ComponentSubtype.Name//////
}
答案 0 :(得分:4)
从HTML调用该函数,一旦收到回调,就将其值存储在JSON对象中,该对象可以用HTML打印。同时在UI中显示加载消息
<强> HTML:强>
{{ getComponentSubtype(component.ID) }}
<td ng-if="componentsSubType[component.ID] != null">
{{ componentsSubType[component.ID] }}
</td>
<td ng-if="componentsSubType[component.ID] == null">Loading Component ...</td>
<强>控制器:强>
function getComponentSubtype(componentId) {
apiService.get('/api/components/' + componentId + '/componentSubtype', config,
function(result) {
if ($scope.componentsSubType == null) {
$scope.componentsSubType = {};
}
$scope.componentsSubType[componentId] = result;
},
function() {
if ($scope.componentsSubType == null) {
$scope.componentsSubType = {};
}
$scope.componentsSubType[componentId] = "Load Failed";
});
}
注意:我假设您在HTML中从循环中获取component
(ng-repeat
)
答案 1 :(得分:1)
...
<td>{{myvariable}}</td>
在您的控制器中......
angular.module('yourApp').controller('ControllerName', function($scope, apiService) {
$scope.myvariable = 'please wait';
function initComponent(id) {
apiService.get('/api/components/' + id + '/componentSubtype').then(function(response) {
$scope.myvariable = response;
}).catch(function(failedResponse) {
// handle failure here
console.log('oops', failedResponse);
});
}
initComponent(500);
});
答案 2 :(得分:0)
这很可能并不理想,但我需要了解更多有关代码的信息,以获得更好的解决方案。
您可以使用对象存储类型并访问模板中的类型:
<td>{{ componentSubtypes[component.id] }}</td>
为每个组件ID调用getComponentSubtype
:
$scope.componentSubtypes = {};
components.forEach(function(component) {
getComponentSubtype(component.id);
});
function getComponentSubtype(componentId) {
apiService.get('/api/components/' + componentId + '/componentSubtype', config,
getComponentSubtypeCompleted(componentId),
getComponentSubtypeFailed);
}
// Using a closure here for the id
function getComponentSubtypeCompleted(id) {
return function(result) {
$scope.componentSubTypes[id] = result;
// ...
}
}