how to display model object in angular js? - javascript

Here is my RestController Class
#RestController
#RequestMapping(value="/user")
public class Test {
#RequestMapping(value="/{userEmailId}",method=RequestMethod.GET)
public ModelAndView getUser(#PathVariable("userEmailId") String userEmailId){
//something goes here and get User class object
ModelAndView mav=new ModelAndView("showuser");
mav.addObject("user", user);//user is User class object
return mav;
}
}
I want to display this user object in showuser.jsp using Angular JS How can I do that?

Below is sample example assuming your user object have firstname and lastname:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.3/angular.min.js"></script>
</head>
<div ng-app="myApp" ng-controller="userController">
<form action="demo_form.html">
First name: <input type="text" name="fname" ng-model="fname"><br>
Last name: <input type="text" name="lname" ng-model="lname"><br>
</form>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('userController', function($scope, $http) {
$http({
method : "GET",
url : "/user/xyz#a.com"
}).then(function mySucces(response) {
$scope.fname = response.fname;
$scope.lname = response.lname;
}, function myError(response) {
//handling error
});
});
</script>

Related

$http.put request changing into OPTIONS request in AngularJS 1.3.15 [duplicate]

This question already has answers here:
Angular $http is sending OPTIONS instead of PUT/POST
(2 answers)
Closed 5 years ago.
I'm new to the AngularJS. I'm using AngularJS 1.3.15 version. When I try to call an api with PUT method, It's generating OPTIONS request. I don't know where I'm doing mistake. I tried so many methods which is suggested in Stockoverflow, but still I'm not getting anything. Please help me to resolve this issue. below are my Controller, Models, html files and Chrome developer tool network activity screenshot.
Controller file users.js
'use strict';
mmlApp_users.config(['$routeProvider', function($routeProvider){
$routeProvider
.when('/users/update/:userId', {
templateUrl: 'views/users/update.html',
controller: 'update',
resolve: {
user: function(users, $route){
var userId = $route.current.params.userId
return users.getUser(userId);
}
}
})
.otherwise({
redirectTo: '/users/index'
});
}]);
Model file - users.js
'use strict';
mmlApp_users.factory('users', ['$http', '$location', '$route', function($http, $location, $route){
var obj = {};
obj.getUser = function(userId){
return $http.get(serviceBase + 'users/view/'+userId);
};
obj.updateUser = function(user){
var config = {
headers: {
'Content-Type': 'application/json'
}
};
var userParams = {
first_name: user.first_name,
last_name: user.last_name,
email: user.email,
password: user.password,
address: user.address,
state: user.state,
city: user.city,
zip_code: user.zip_code
};
$http.put(serviceBase + 'users/update/'+user.id+'?access-token=8e0bb9b3-b35f-4d30-943d-6028c0b85c13', userParams, config)
.then(successHandler).catch(errorHandler);
function successHandler(){
$location.path('/users/index');
}
function errorHandler(){
alert('Oops! Somthing went wrong.');
//$location.path('/users/create');
}
};
return obj;
}]);
Views - update.html
<div>
<h1>{{title}}</h1>
<p>{{ message}}</p>
<form role="form" name="myForm">
<div class="row">
<div class= "form-group col-md-6" ng-class="{error: myForm.first_name.$invalid}">
<label> First Name: </label>
<div>
<input name="first_name" ng-model="user.first_name" type= "text" class= "form-control" placeholder="First Name" required/>
<span ng-show="myForm.first_name.$dirty && myForm.first_name.$invalid" class="help-inline">First Name Required</span>
</div>
</div>
<div class= "form-group col-md-6" ng-class="{error: myForm.last_name.$invalid}">
<label> Last Name: </label>
<div>
<input name="last_name" ng-model="user.last_name" type= "text" class= "form-control" placeholder="Last Name" required/>
<span ng-show="myForm.last_name.$dirty && myForm.last_name.$invalid" class="help-inline">Last Name Required</span>
</div>
</div>
</div>
....
....
....
Cancel
<button ng-click="updateUser(user);" ng-disabled="myForm.$invalid" type="submit" class="btn btn-default">Submit</button>
</form>
</div>
In chrome developer tool network activity screenshot -
try in your factory:
(function () {
'use strict';
mmlApp_users.factory('users', ['$http', '$location', '$route','$httpParamSerializer',
function ($http, $location, $route, $httpParamSerializer) {
var obj = {};
obj.getUser = function (userId) {
return $http.get(serviceBase + 'users/view/' + userId);
};
obj.updateUser = function (user) {
var userParams = {
first_name: user.first_name,
last_name: user.last_name,
email: user.email,
password: user.password,
address: user.address,
state: user.state,
city: user.city,
zip_code: user.zip_code
};
var req = {
method: 'PUT',
url: serviceBase + 'users/update/' + user.id + '?access-token=8e0bb9b3-b35f-4d30-943d-6028c0b85c13',
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
},
data: $httpParamSerializer(userParams)
};
$http(req)
.then(successHandler)
.catch(errorHandler);
function successHandler() {
$location.path('/users/index');
}
function errorHandler() {
alert('Oops! Somthing went wrong.');
//$location.path('/users/create');
}
};
return obj;
}]);
})();
And Goog Lock :)

AngularJS: Get template attribute value in controller

I am a newbie of angularjs using version 1.6.4. I am using this module leon/angular-upload for upload functionality, minify version. On successful upload request, server return json object of uploaded file information on onSuccess(response) function as you can see in my user-registration.template.html file. Now i need to take this json object to my controller so that i can save this information in my database. Below is the few lines of my code.
user-registration.template.html:
<form role="form">
<div class="form-group float-label-control">
<label>Name</label>
<input type="text" placeholder="Name" class="form-control" ng-model="model.user.name">
</div>
<!-- leon/angular-upload -->
<div upload-button
url="/user_uploads"
on-success="onSuccess(response)"
on-error="onError(response)">Upload</div>
<div class="text-center">
<button type="button" class="btn btn-default" ng-click="model.save(model.user)">Save</button>
</div>
</form>
My component "user-registration.component.js":
(function(){
"use strict";
var module = angular.module(__appName);
function saveUser(user, $http){
var url = user.id > 0 ? __apiRoot + "/users/" + user.id : __apiRoot + "/users";
var dataObj = {
payload: JSON.stringify(user),
_method: "PUT"
}
return $http.post(url, dataObj);
}
function controller($http){
var model = this;
model.user = null;
model.save = function(user){
console.log(JSON.stringify(user));
saveUser(user, $http).then(function(response){
alert(response.data.msg);
});
}
}
module.component("userRegistration", {
templateUrl: "components/user-registration/user-registration.template.html",
bindings: {
value: "<"
},
controllerAs: "model",
controller: ["$http", controller]
});
}());
Try to put your server response data to rootScope model for Exempel :
$rootScope.serveResponse = response ;
and with this rootScope you can share your variable data between controller

Unknown provider: myFactProvider <- myFact <- thirdCtrl

Hi all my requirement is to share input field data using get set method in factory with another controller.
angular.module('dataModule',[]).factory('myFact',function($http){
var user = {};
return {
getDetails: function () {
return user ;
},
setDetails : function (name,add,number) {
user.name = name;
user.add = add;
user.number = number;
}
}
});
Here is controller code.
angular.module('dataModule',[]).controller('thirdCtrl',function(myFact,$scope) {
$scope.saw=function(){
alert("hello get set method");
$scope.user=myFact.user.getDetails();
console.log(user);
};
});
Here is my html code
<div ng-controller="thirdCtrl">
<h1>hello gaurav come here after click one.</h1>
<div>
<lable>NAME</lable>
<div><input type="text"ng-model="user.name"></div>
</div>
<div>
<lable>ADDRESS</lable>
<div><input type="text"ng-model="user.add"></div>
</div>
<div>
<lable>MOBILE</lable>
<div><input type="number"ng-model="user.number"></div>
</div>
</br>
</br>
<button type="button" ng-click="saw()">Click</button>
</div>
Here is my app.js
var app = angular.module('sapient',['ui.router','dataModule']);
app.config(['$stateProvider','$urlRouterProvider',function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('one', {
url: '/one',
templateUrl: 'view/sap.html',
controller: 'sapCtrl'
})
.state('two', {
url: '/two',
templateUrl: 'view/two.html',
controller: 'secondCtrl'
})
.state('three', {
url: '/three',
templateUrl: 'view/three.html',
controller: 'thirdCtrl'
});
$urlRouterProvider.otherwise('two');
}])
Any Suggestions
Thanks in advance
The problem is you're recreating the module. Remove the [] (array of module dependencies) to make angular retrieve the previously created module, rather than create a new one.
Change:
angular.module('dataModule',[]).controller('thirdCtrl',function(myFact,$scope)
To:
angular.module('dataModule').controller('thirdCtrl',function(myFact,$scope)

How to use ng-model / $scope with Angular Factory and Controller

// SERVICES
app.factory('searchFactory', ['$http', function($http) {
return $http.post("/api", { tag: "food" });
}]);
// CONTROLLERS
app.controller('MainController', ['$scope', 'searchFactory', function ($scope, searchFactory) {
$scope.submit = function () {
searchFactory.then(function(response) {
$scope.recipeData = JSON.parse(response.data);
});
};
// HTML
<form ng-submit="submit()">
<div class="form-group">
<input type="text" ng-model="recipeTag" class="form-control" />
<input type="submit" class="btn btn-primary" value="Find Recipes" />
</div>
</form>
Does anyone know how I can use $scope.recipeTag from ng-model to replace "food" in the factory? I need to be able to pass the form input as a parameter into the factory.
you need to create a funtion that expects a parameter in your factory.
Example:
var factory= {
post: function(customTag) {
return $http.post("/api", { tag: customTag });
}
};
return factory;

Passing multiple object values between controllers using a service

I have two controllers and setup a service to hold the data:
var myApp = angular.module('myApp', []);
myApp.factory('Data', function() {
return { message: "This is a message from a service", Type: "This is a type from a service" }
});
function FirstCtrl($scope, Data) {
$scope.data = Data;
}
function SecondCtrl($scope, Data) {
$scope.data = Data;
}
In my HTML, I have inputs to bind these values:
<div ng-controller="FirstCtrl">
<input type="text" ng-model="data.message">
<h1>{{ data.message }}</h1>
</div>
<div ng-controller="SecondCtrl">
<input type="text" ng-model="data.type">
<h1>{{ data.type }}</h1>
</div>
However, all im getting back from the service is my data.message and nothing for data.type.
Why is this?
It is a simple type error. The Factory returns a Data object with 'Type' as a key. In your HTML you have used 'type' as the key instead of 'Type'.

Categories

Resources