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

时间:2016-05-07 01:50:36

标签: javascript angularjs drop-down-menu request

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

$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>

1 个答案:

答案 0 :(得分:0)

您的版本应该有效。我已经包含了一个完全剥离的示例,以演示数据绑定效果。如果没有关于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以进行完整演示。从选择中的2个项目开始,每次按下Add按钮时添加一个项目。除了设置$ scope变量之外,不需要任何工作。

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