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
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.
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.
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
Related
Hi when i run the spring angular app it is showing GET http://localhost:8080/cyclone/admin/admin/cycle 404 (Not Found) . i don't have any idea where the second admin came from on the url.
access url Cycle and the html page under WEB-INF/views/admin/cycle.html
Angular root setup
App.config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/cycle', {
templateUrl: 'admin/cycle.html',
controller: 'CycleController'
});
}]);
My Spring controller
#Controller
#RequestMapping(value = "/admin")
public class AdminController {
#RequestMapping("/cycle.html")
public String getCarPartialPage() {
return "admin/cycle";
}
}
Change the code like below
$routeProvider.when('/cycle', {
templateUrl: 'cycle.html',
controller: 'CycleController'
});
and in spring controller
#RequestMapping(value = "/cycle.html", method = RequestMethod.GET)
public String getCarPartialPage() {
return "admin/cycle";
}
Change your getCarPartialPage() method to return "cycle"
I am trying to implement nested states using stateProvider. Facing issues while loading the nested states using url-routing. I have created two independent states and 2 nested states for one of the inndependent state. Please check the state configuration below:
.state('state1',{
url : "/page1",
templateUrl : "/views/page1.html",
contoller : 'page1ctrl'
})
.state('state2', {
url : "/page2",
templateUrl : "/views/page2.html",
controller : 'page2ctrl'
})
state('state2.nestedstate1', {
url : "/:nestedstate1", //passing as parameter
templateUrl : "/views/temp1.html",
controller : 'page2ctrl'
})
.state('state2.nestedstate1.nestedstate2', {
url : "/nestedstate2/:param1/:param2",
templateUrl : "/views/temp2.html",
controller : 'ctrl'
})
Issue : If I try to load complete page directly using complete url index.html/page2/nestedstate1/nestedstate2/fname/lname, it will first load data from last child state nestedstate2 and then fall back to its parent state 'nestedstate1' and also updates the url to index.html/page2/nestedstate1.
Required behaviour is to execute parent state first then the child state. For Example, nestedstate1 is necessary to load before nestedstate2.
Please suggest if I am missing any configuration.
Thanks
I created working example here. It is 1:1 to your scenario.
In the above script I found only one typo:
// missing dot
state('state2.nestedstate1', {
// should be
.state('state2.nestedstate1', {
The example is then working, while using these calls:
<a ui-sref="state1">
// ui-sref
<a ui-sref="state2">
<a ui-sref="state2.nestedstate1({nestedstate1: 'theNestedStateA'})">
<a ui-sref="state2.nestedstate1.nestedstate2({
nestedstate1: 'theNestedStateB', param1: 'value1' ,param2: 'value2'})">
// href
<a href="#/page2">
<a href="#/page2/nestedstate0">
<a href="#/page2/nestedstate1/nestedstate2/fname/lname">
All the rest should be almost the same. You can compare this working version with your local code, to find out what is wrong...
Check it here
Extend
Each view in (state2 chain) is provided with its own controller
.state('state2', {
url : "/page2",
templateUrl : "/views/page2.html",
controller : 'page2ctrl'
})
.state('state2.nestedstate1', {
url : "/:nestedstate1", //passing as parameter
templateUrl : "/views/temp1.html",
controller : 'page2Nestedctrl'
})
.state('state2.nestedstate1.nestedstate2', {
url : "/nestedstate2/:param1/:param2",
templateUrl : "/views/temp2.html",
controller : 'ctrl'
})
And they are like this:
.controller('page2ctrl', ['$scope', function ($scope) {
console.log('page2ctrl')
}])
.controller('page2Nestedctrl', ['$scope', function ($scope) {
console.log('page2Nestedctrl')
}])
.controller('ctrl', ['$scope', function ($scope) {
console.log('ctrl')
}])
Then when navigating to url: page2/nestedstate1/nestedstate2/fname/lname, we can see this in console:
page2ctrl
page2Nestedctrl
ctrl
And that should show, that all the states are initiated in expected order
so, following best practice I've started using ng-strict-di. It's worked well so far, but I have hit the following problem using ui-router
// nested list with custom controller
.state('dashboard.list', {
url: '/list',
templateUrl: 'partials/dashboard-list.html',
controller: function($scope) {
$scope.dogs = ['Bernese', 'Husky', 'Goldendoodle'];
}
})
this causes angular to barf with the "Error: error:strictdi
Explicit annotation required" error.
I know that I should be using the inline bracket notation, or $inject, but obviously can't put it in this code as is.
I was thinking that I could declare the controller in another part of the script, with $inject and then just reference it in the code ?
function GoodController1($scope) {
}
GoodController1.$inject = ["$scope"];
and then
// nested list with custom controller
.state('dashboard.list', {
url: '/list',
templateUrl: 'partials/dashboard-list.html',
controller: GoodController1
})
would this work ? Are there any problems with this approach ?
There are no problems, with this approach. I am using typescript, and the generated syntax of controlelr class is almost the same as yours.
Here is a working plunker
...
// the contoller funciton to be instantiated
// by angular using new
var GoodController1 = function($scope){
$scope.title = "good title";
};
// set of dependencies
// (in typescript that would be a static property)
GoodController1.$inject = ["$scope"];
// before angular 2.0, this is the must
// we still have to register controller in the module
app
.controller('GoodController1', GoodController1)
...
and later in state:
.state('good', {
url: "/good",
templateUrl: 'tpl.html',
controller: "GoodController1",
})
check it here
I am new to javascript, typescript and AngularJS and am currently trying to learn the language by building a sample app.
I am an experienced programmer coming from an Actionscript / Flex background.
As I come from Actionscript I really like the 'controller as' syntax as I don't need to deal with the untyped $script object floating around and doing magic stuff that I can't control (my opinion as someone who distrusts javascript ;-).
In this example though I want to make an html page that displays loading info for a variety of different services that will load data. I envisage using this html fragment as a header at the top of a page which could show loading info for a list of albums, a list of images or even just when you're logging in.
This example is not what I would do in production as there are a number of things that I do not like about this approach but this is a learning exercise so I am trying to figure out how this would work.
I have the following TypeScript code:
LoadingModule
export interface ILoadable
{
isLoading : boolean;
isLoaded : boolean;
loadingMessage : string;
errorMessage : string;
}
export class LoadingController implements ILoadable
{
// Constructor
constructor( private service? : ILoadable )
{
}
// Properties
public get isLoading() : boolean
{
return this.service ? this.service.isLoading : true;
}
public get isLoaded() : boolean
{
return this.service ? this.service.isLoaded : false;
}
public get loadingMessage() : string
{
return this.service ? this.service.loadingMessage : "Loading...";
}
public get errorMessage() : string
{
return this.service ? this.service.errorMessage : "There was a fault.";
}
}
App
app.config( ($routeProvider) => {
$routeProvider
.when( '/albums', { templateUrl: './pages/albums.html' } )
.when( '/album', { templateUrl: './pages/album.html' } )
.when( '/pictures', { templateUrl: './pages/pictures.html' } )
.when( '/loggingIn', { templateUrl: './pages/loading.html', controller : "loginController" } )
.when( '/loadingAlbums', { templateUrl: './pages/loading.html', controller : "loadingAlbumsController" } )
.when( '/404', { templateUrl: './pages/404.html' } )
.otherwise( { redirectTo: '/loggingIn' } )
});
app.controller( "loginController", [ "authenticator", Picasa.LoadingController ] );
app.controller( "loadingAlbumsController", [ Picasa.LoadingController ] );
Loading.html
<div ng-controller="loginController as loadable">{{loadable.loadingMessage}}</div>
This all works great but I always get the loginController passed into the html page. This is obviously because I refer to it in the html page so this overrides me specifying a controller in the route provider setup.
My question is can I use the "controller as" setup in an html page that will have different controllers injected?
I want the html page setup to work with an ILoadable.
I don't want to have to inject $scope into my controller and set properties on it.
Ideally I'd be able to inject a service directly into the html page so that I don't have to have the controller wrapper.
Many Thanks
You can use the controllerAs syntax for the routing:
$routeProvider
.when( '/loggingIn', { templateUrl: './pages/loading.html', controller : "loginController", controllerAs: 'login' } )
Your Index.html should have ng-view="" which is where the view will be substituted in.
This will enable you to do {{login.message}} in the views.
I have a route with parameter like this
var app = angular.module("myapp", ["ngRoute"]);
app.config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) {
$locationProvider.hashPrefix("!").html5Mode(true);
$routeProvider
.when('/sukien', { templateUrl: '/app/views/sukien/index.html' , controller: 'eventCtrl' })
.when('/sukien/:id', { templateUrl: function (params) { return '/app/views/sukien/index.html?id=' + params.id }, controller: 'eventCtrl' })
}])
why /sukien works and /sukien/:id doesn't ? indeed, angularjs seems not to understand what it is. "Uncaught TypeError: undefined is not a function"
/sukien/333 => failed to work.
You are mixing template url, state of your application and search parameters it seems.
The templateUrl tells angularjs where to look for the html file : it will very unlikely depend on the params.id and be set via a function, but will rather be a constant.
It has nothing to see with the url that the user sees in their browser.
For example : '/app/views/sukien/suiken.html'
The url the user sees will be something like :
.../suiken/1223445
And you can then access the id in your controller via $routeParams.id