使用angularJs中的数据库数据源刷新下拉列表

Refresh dropdown list with db datasource in angularJs

本文关键字:数据源 刷新 下拉列表 数据库 angularJs 使用      更新时间:2023-09-26

我有一个从数据库中获取元素的下拉列表,问题是我想向列表中添加新元素,并且能够在不刷新页面的情况下查看添加的新元素。我试图删除旧列表,并发出新的http请求,直接从数据库中获取新元素,但不幸的是,我在某个地方遗漏了一些东西。这是代码:

$http.post('/api/adminPanel/createTagType', tagDetails).then(function (response) {
            console.log("Response from Controller: " + JSON.stringify(response));
            if(response.data==='success'){
                $http.get('api/adminPanel/getTags').then(function(result){
                    try{
                        $scope.tags = result.data.tags;
                        console.log($scope.tags);
                    }catch(error){
                        console.log(error);
                    }
                });
            }
        });

首先我给post一个新的值,然后检查请求是否成功,然后我发出新的get请求以获得新的列表。你们能帮我解决这个问题吗?

更新

这是html代码:

    <select name= "inputTag" id= "inputTag" class="form-control" ng-model="Tag">
    <option value="">Select Tag Type</option>
    <option ng-repeat="tag in tags" value="{{tag.idtagTypes}}" >{{tag.tagName}}</option>
</select><br/>
 <button class="btn btn-primary" ng-click="addTag()">Add Tag</button>

您的版本应该可以工作。我已经包含了一个完全剥离的示例来演示数据绑定效果。如果没有更多关于API返回、控制器设置、角度配置等的信息,这将很难具体诊断。

<body ng-app="app">
  <div ng-controller="ctrl">
    <select>
      <option ng-repeat="tag in tags">{{ tag.name }}<option>
    </select>
    <button ng-click='update()'>Add</button>
  </div>
</body>

Javascript

angular.module('app', [])
  .controller('ctrl', function($scope){
    // initial scope.tag value
    $scope.tags = [{name:1}, {name: 2}];
    $scope.update = function(){
      // update scope.tag variable ...
      $scope.tags.push({ name: $scope.tags.length + 1});
    };
});

我已经包含了jsbin作为一个完整的演示。从select中的2个项目开始,每次按下Add按钮时添加一个。除了设置$scope变量之外,不需要其他工作。

这可以很容易地扩展到包括$http请求,而不是我对数据的虚假更新。