繁体   English   中英

单击按钮时加载新的json url,并更新Angular中的View

[英]Loading new json url on button click and updating View in Angular

抱歉,这个问题已经存在,但我找不到。

我正在开发Angular项目,并且已经使用http加载了外部JSON文件。 使用ngRepeat显示此数据。

我想在单击按钮时使用不同的参数再次加载文件并更新ngRepeat

JavaScript的:

angular.module('App', [])
    .controller('ResultsCtrl', function($scope, $http) {
        $http.get(searchUrl).then(function(res){
            $scope.markersAll = res.data;     
        })
        .success(function(data, status, headers, config) {
            $scope.markersAll = res.data;
        })
        .error(function(data, status, headers, config) {
            // something went wrong
        });
});

HTML

<div ng-repeat="marker in markersAll">
    <h4>{{marker.org}}</h4>
</div>

<select id="Category_Selection">
    ...
</select>
<input type="button" onClick="searchLocations()" value="Search"/>

我试图将JS包装在一个函数中,然后单击按钮时调用它,但这没有用。 如何使用新的http GET请求更新$ scope.MarkersAll? 还是应该以其他方式加载此数据?

编辑:更新为使用“ ng-click ”而不是“ onClick ”。

顺便说一句,使用controllerAs语法而不是直接绑定到$ scope是一个好习惯。

 angular .module('App', []) .controller('ResultsCtrl', function($scope, $http) { $scope.markersAll = []; //initialize to empty array so ng-repeat doesn't complain $scope.searchLocations = searchLocations; searchLocations(); //perform a search on load function searchLocations() { $http.get(searchUrl).then(function(res) { $scope.markersAll = res.data; }); } }); 
 <div ng-repeat="marker in markersAll"> <h4>{{marker.org}}</h4> </div> <select id="Category_Selection"> ... </select> <input type="button" ng-click="searchLocations()" value="Search" /> 

在您的angular js code您可以尝试以下操作:

 angular.module('App', [])
 .controller('ResultsCtrl', function($scope, $http) {
    $http.get(SITE_URL).success(function(data) {
       $scope.markersAll=data;
    });
   $scope.myproject = function(marker) {
      $http.get(SITE_URL?marker="+marker).success(function(data){
        $scope.markersall1=data;
  });

在您的html代码中,您可以添加以下代码:

 <div ng-repeat="marker in markersAll">
   <h4>{{marker}}</h4>
 </div>

 <div ng-repeat="marker in markersAll1">/*data come using ajax on button click event*/
   <h4>{{marker}}</h4>
 </div>
 <select ng-model="marker">
   <option ng-repeat="marker in markersAll">{{marker}}</option>
 </select>
 <button  type="button" ng-click="myFunction(marker)">

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM