简体   繁体   English

AngularJs如何从Spring MVC控制器访问Model Attribute值

[英]AngularJs how to access Model Attribute value from Spring MVC controller

I have a Spring MVC Controller returning a page with an attribute as followed 我有一个Spring MVC Controller返回一个带有如下属性的页面

@RequestMapping(method = RequestMethod.GET, value = "/create")
public ModelAndView getAddAccountView() {
    ModelAndView model = new ModelAndView("protected/accounts/AccountAddView");
    List<Client> clients=clientService.findAll();
    model.addObject("listClients", clients);
    return model;
}

Client is a @Entity 客户是@Entity

in my AccountAddView.jsp file, i'm trying to use the ng-init as follow: 在我的AccountAddView.jsp文件中,我正在尝试使用ng-init,如下所示:

<div class="row-fluid" ng-controller="accountsController as ctrl" ng-init="clients=${listClients}">

and in my app.js, in my controller, i try to access the list of client as followed 在我的app.js中,在我的控制器中,我尝试访问客户端列表,如下所示

var listOfClients=$scope.clients;

but I'm still getting the following error 但我仍然收到以下错误

angular.min-1.5.3.js:116 Error: [$parse:lexerr] http://errors.angularjs.org/1.5.3/$parse/lexerr?p0=Unexpected%20nextharacter%20&p1=s%2033-33%20%5B%40%5D&p2=clients%3D%5Bsoftbank.ui.model.Client%4042%2C%softbank.ui.model.Client%4041%2C%softbank.ui.model.Client%4043%5D
at Error (native)
at http://localhost:8080/softbank/resources/js/angular.min-1.5.3.js:6:416
at gc.throwError (http://localhost:8080/softbank/resources/js/angular.min-1.5.3.js:212:149)
at gc.lex (http://localhost:8080/softbank/resources/js/angular.min-1.5.3.js:211:16)
at Object.ast (http://localhost:8080/softbank/resources/js/angular.min-1.5.3.js:216:103)
at Object.compile (http://localhost:8080/softbank/resources/js/angular.min-1.5.3.js:225:232)
at hc.parse (http://localhost:8080/softbank/resources/js/angular.min-1.5.3.js:252:380)
at e (http://localhost:8080/softbank/resources/js/angular.min-1.5.3.js:123:317)
at m.$eval (http://localhost:8080/softbank/resources/js/angular.min-1.5.3.js:142:463)
at pre (http://localhost:8080/softbank/resources/js/angular.min-1.5.3.js:271:500)

please what is wrong here. 请问这里有什么问题。 why is ng-init generating this errors? 为什么ng-init会产生这个错误? thanks in advance for your answer. 提前感谢您的回答。

I'm just starting with Angular with Spring so what I'll do is explain how I did it and you can see if it's a viable option for you. 我刚开始使用Angular和Spring,所以我要做的就是解释我是如何做到的,你可以看看它是否适合你。

For one, I didn't try to go through the ModelAndView for my data. 首先,我没有尝试通过ModelAndView获取我的数据。 I let my "regular" controller return the view but got my data via the angular controller and service along with a @RestController on the Spring side (that's two separate Spring controllers then). 我让我的“常规”控制器返回视图,但通过角度控制器和服务以及Spring端的@RestController我的数据(那时是两个独立的Spring控制器)。

To return only the view you have at least two options that I'm aware of. 要仅返回视图,您至少有两个我知道的选项。 One, you can just return a ModelAndView without a model like so: 一,你可以在没有这样的模型的情况下返回ModelAndView

public ModelAndView yourView() {
    return new ModelAndView("yourView");
}

Or two, return the name of the view as a string like so: 或者两个,将视图的名称返回为字符串,如下所示:

public String yourView() {
    return "yourView";
}

In both cases you'd obviously need the correct @RequestMapping . 在这两种情况下,您显然需要正确的@RequestMapping

In my view I had an angular controller function that made a call to my associated angular service which in turn called my @RestController and so on. 在我看来,我有一个角度控制器函数,它调用我的相关角度服务,然后调用我的@RestController ,依此类推。 I initiated the data like so: 我发起了这样的数据:

ng-controller="MyController as ctrl" ng-init="ctrl.allThings()"

Examples of the code: 代码示例:

Angular controller: 角度控制器:

self.allThings = function () {
        ThingService.things()
            .then(
                function (data) {
                    self.things = data;
                },
                function (errResponse) {
                    console.error("Error retrieving thing list");
                }
            );
    };

Angular service: 角度服务:

    things: function() {
        return $http.get('/things')
            .then(
                function(response) {
                    return response.data;
                },
                function (errResponse) {
                    return $q.reject(errResponse);
                }
            );
    },

Spring REST controller: Spring REST控制器:

@RequestMapping(value = "/things", method = RequestMethod.GET)
public List<Thing> things() {
    return thingService.findAll();
}

I imagine you know the remaining code for the Spring side. 我想你知道Spring方面剩下的代码。 Jackson will handle all the object conversions for you. 杰克逊将为您处理所有对象转换。

Old Post but still I would like to answer so that anyone who is using Angular with Spring MVC get some help. Old Post但我仍然想回答,任何使用Angular和Spring MVC的人都会得到一些帮助。
Using model attribute is a challenge with Angular. 使用模型属性是Angular面临的挑战。 Earlier I was setting employee data in model attribute like mav.addObject("employee",employee) , but when I was trying to use ${employee} inside the jsp, Angular wasn't able to set the java object using ng-init directive because it was expecting a java script object. 之前我在模型属性中设置员工数据,如mav.addObject("employee",employee) ,但是当我尝试在jsp中使用${employee} ,Angular无法使用ng-init设置java对象指令,因为它期待一个java脚本对象。 So I set json inside the model Attribute mav.addObject("employeeJson", empJson) and parsed it using json.Parse() to convert it into Java Script Object and was able to use it with Angular expressions on the jsp 所以我在模型Attribute mav.addObject("employeeJson", empJson)设置了json mav.addObject("employeeJson", empJson)并使用json.Parse()将其解析为Java Script Object,并且能够将它与jsp上的Angular表达式一起使用
Below are the steps which I followed: 以下是我遵循的步骤:
1. Spring Controller 1.弹簧控制器
In your controller, set json in the model attribute. 在控制器中,在model属性中设置json。 For eg 例如
mav.addObject("employeeJson", empJson);
Make sure before adding it to ModelAttribute , replace quotes with html entity " otherwise there will be error while parsing the json empJson.replaceAll("\\"", "\\&\\quot;"); 在将其添加到ModelAttribute之前确保用html实体替换引号“否则在解析json empJson.replaceAll("\\"", "\\&\\quot;");会出错empJson.replaceAll("\\"", "\\&\\quot;");
2. Jsp 2. Jsp
Use angular init directive, data-ng-init="yourController.getEmployeeData('${employeeJson}')" 使用angular init指令, data-ng-init="yourController.getEmployeeData('${employeeJson}')"
3. In Angular js 3.在Angular js
parse this json to get the json 解析这个json来获取json
var vm = this;
vm.employee = {};
vm.getEmployeeData = function(employeeJson){, vm.employee = JSON.parse(employeeJson); };
4. Inside jsp 4.在jsp里面
I can access employee name as {{yourController.employee.firstName}} 我可以访问员工姓名{{yourController.employee.firstName}}

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

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