Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting data from Spring MVC in Angular JS in the initial view call

I am new to Angular JS, I have created a Spring MVC web application with Angular JS, I know that from view we can call REST services from Angular JS using resource, restangular, http , But say in Spring form the Controller a view is been triggered and for loading the datas through angular within the view again a REST call from angular is been called from view to the server and gets the datas thereafter for loading, Instead is there any way to pass the json object while triggering the view from Spring controller to the Angular JS at the first time itself.

enter image description here

I have done a similar thing, its working fine but don't know whether its a good approach or not.

Spring controller

@RequestMapping("/getemployee")
public ModelAndView helloWord(){
   JSONArray employeeJsonArray = // contains all the information of the employee
   return new ModelAndView("employee", "employee",employeeJsonArray);
}

employee.jsp

<html ng-app="myApp">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Spring 3.0 MVC Series: Hello World</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular.min.js"></script>
<script>
var app = angular.module('myApp', []);
app.controller('MyCtrl', function($scope) {
    $scope.employee = [];
    $scope.loadData = function(employee)
    {
        $scope.employee = JSON.parse(employee);
    };
});
</script>
</head>
<body ng-controller="MyCtrl">
{{loadData('${employee}')}}

 <input type="text" ng-value="employee[0].name"/>
</body>
</html>
like image 642
Alex Man Avatar asked Jun 08 '14 13:06

Alex Man


2 Answers

Angular really shines when you use it in a "single" page application, so I would suggest using it as you suggested in your "existing approach" as it moves you closer to a single page app design, however, if you are just trying to get some of the features of Angular in an existing request/response application, then you could send your html payload with the data in ng-init as this page demonstrates. It's a RoR example, but I think the point is clear. I think it is a bit of hack, but should get the job done.

   <body ng-init="angularVariable = ${variableFromServer}">
     html/angular ...
   </body>
like image 117
dspies Avatar answered Oct 22 '22 12:10

dspies


I recently switched to using angular, the beauty of it is you can ditch jsp's entirely and just have static html as the frontend. Served as a static resource by spring.

To initially populate your form/tables/whatever - lots of different options do it in javascript/angular. But its nice to keep your view seperate from your controllers (ie don't use jsp's).

like image 45
NimChimpsky Avatar answered Oct 22 '22 12:10

NimChimpsky