angularjs从html调用函数返回值

angularjs call function from html return value

本文关键字:函数 返回值 调用 html angularjs      更新时间:2023-11-16

我是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//////
}

从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中,您从循环(ng-repeat)中获得component

在HTML中。。。

<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);
});

这可能并不理想,但我需要了解更多关于您的代码的信息,以获得更好的解决方案。

您可以使用一个对象来存储类型并访问模板中的类型:

<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;
       // ...
   }
}