2016-12-26 78 views
0

我想在角度js中獲取模型數據,但無法獲取它。我在spring mvc端打印了這個值。數據被存儲並且通過給定的鍵被成功檢索到了。可以告訴我如何實現這個功能。在角度js控制器中獲取ModelAndView數據

我的控制器 -

@RequestMapping(value = "/home.web", method = RequestMethod.GET, produces = { 
      "application/json" }) 

    public ModelAndView getUSCity(@RequestParam ("statechoice") String statechoice) { 


     List<String> msa = new ArrayList<String>();  
     msa = msaService.getMsaCodes(statechoice); 


     /*ModelAndView model = new ModelAndView("Home"); 
     model.addObject("cities",msa); 
    System.out.println(model.getModel().get("cities"));*/ 

     //return msa; 
     return new ModelAndView("Home", "cities",msa); 
    } 

我的角度JS -

function MyController($scope, $http) { 

     $scope.getPersonData = function() {   
      $http({ 
       method : 'GET', 
       url : 'home.web' 
      }).success(function(data, status, headers, config) { 
       alert(data); 
       $scope.cities = data; 
      }).error(function(data, status, headers, config) { 
       console.log("error"); 
       // called asynchronously if an error occurs 
       // or server returns response with an error status. 
      }); 

     }; 
    }; 

回答

0

分割你的代碼的控制器和服務,因爲你不應該做的cotroller API調用直接(最好的情況下)。應該使用服務。控制器僅用於控制模型以在視圖中顯示它。

myService.js

app.service('myService', ['$http', '$q', function($http, $q){ 
    return { 
      getPersons: function(obj) { 
        var deferred = $q.defer();  
        $http({ 
         method : obj.method, 
         url : obj.url 
        }).then(function(response) { 
         deferred.resolve(response); 
        }, function(error) { 
         alert(error); 
         deferred.reject(error); 
         // called asynchronously if an error occurs 
         // or server returns response with an error status. 
        }); 
        return deferred.promise(); 

       }; 
     } 
    }); 

myController.js

function MyController('MyController', ['$scope', 'myService', function($scope, myService){ 
     $scope.persons = []; 
     var obj = {method: 'GET', url: 'home.web'}; 
     myService.getPersons(obj).then(function(response){ 
      $scope.persons = response.data // or $scope.persons = response check yourself 
     }, function(error){ 
      alert(error); 
     }) 
    }]);