Saurabh
Saurabh

Reputation: 7833

ng-init not working angularjs

I am getting parse error

Syntax Error: Token '{' is an unexpected token at column 8 of the expression [user= ${user}] starting at [{user}].

home.html

 <body ng-controller="mainCtrl" ng-init="user= ${user}">

Referring this example ,I am sending model to angularjs Getting data from Spring MVC in Angular JS in the initial view call.

controller.js

angular.module('userSystem', [ 'ngRoute' ]).config(

  function($routeProvider, $httpProvider) {

    $routeProvider.when('/', {
      templateUrl : 'home.html',
      controller : 'home'
    }).when('/login', {
      templateUrl : 'login.html',
      controller : 'navigation'
    }).otherwise('/');

}).controller('mainCtrl',
    function($rootScope, $scope, $http, $location, $route) {
})
});

Spring Controller

@RequestMapping(value = "/", method = RequestMethod.GET)
   public  String getIndex(Model model)
   {
     model.addAttribute("user","user");
     return "home";

   }

Please let me know what is wrong here and how to fix it. Thanks

Upvotes: 0

Views: 770

Answers (3)

Saurabh
Saurabh

Reputation: 7833

I had used resolve from angularjs to populate with user details.

$routeProvider.when('/', {
      templateUrl : 'home.html',
      controller : 'home',
      resolve: {
        message: function(messageService){
            var promise= messageService.getMessage();
            promise.then(data){
            allConstants.user=data;
            }
            return promise;
        }
    }
    }).when('/login', {
      templateUrl : 'login.html',
      controller : 'navigation'
    }).otherwise('/');

Here allConstants is a varible accessible by entire application controllers

Upvotes: 0

alxpez
alxpez

Reputation: 151

Try changing your controller, so instead of sending just a String with the view name, you send a ModelAndView object:

@RequestMapping(value = "/", method = RequestMethod.GET)
public ModelAndView getIndex() {

    ModelAndView mv = new ModelAndView("home");
    mv.addObject("user", "USER_NAME");
    return mv;
}

On the other hand, are you using any templating framework (thymeleaf, velocity...)? Cause in that case, your problem may be in how you pick up the model attribute in front-end.

EDIT (as an answer to the templating framework question):

In case you're using thymeleaf, you would need to do something like this in your index.hmtl:

<body ng-controller="mainCtrl as main" data-th-attr="ng-init='main.user=\''+${user}+'\''>

I found myself with this problem in the past.

Upvotes: 1

Phil
Phil

Reputation: 3736

If you remove the curley braces around user and change to this it will remove your syntax error for you:

<body ng-controller="mainCtrl" ng-init="user= $user">

Taken that you're spring code and population of $user is working correctly.

Upvotes: 0

Related Questions