I am trying to learn angularjs.I wan't to share data between two controllers of two different pages. After googling came to know about services and created one service. From one page I am able to call my rest service and able to get data. After I am trying to redirect to different page. URL is changing but page is not loaded. Stuck here. Please find the code below. Anybody can help me where I am doing wrong?
data.html
<!DOCTYPE html>
<html>
<head>
<base href="/">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"> </script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular-route.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular-resource.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.16/angular-resource.min.js"></script>
<script src="app.js"></script>
<script src="usercontroller.js"></script>
<script src="userservice.js"></script>
</head>
<body ng-app="myApp">
<div ng-controller="UserController" >
<form>
<input type="text" name="Name" ng-model="user.userName"> Name <br/>
<input type="text" name="password" ng-model="user.password"> Password <br/>
<button type="submit" ng-click="getUser(user)" >Submit</button>
</form>
data2.html
<!DOCTYPE html>
<html>
<head>
<base href="/">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"> </script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular-route.js"></script>
<script src="app.js"></script>
<script src="usercontroller.js"></script>
<script src="userservice.js"></script>
</head>
<body>
<div ng-controller="UserController2" >
<form>
<input type="text" name="Name" ng-model="user.userName"> Name <br/>
<input type="text" name="password" ng-model="user.password"> Password <br/>
<button type="submit" ng-click="shareUser()" >Submit</button>
</form>
</div>
app.js
var App = angular.module('myApp',['ngRoute','ngResource']);
App.config(['$routeProvider',
function (
$routeProvider
) {
$routeProvider.
when('/home', {
templateUrl: 'data.html',
controller: 'UserController'
}).
when('/welcome', {
templateUrl: '/data2.html',
controller: 'UserController2'
}).
otherwise({
redirectTo: '/home'
});
}]);
usercontroller.js
App.controller('UserController', ['$scope', 'UserService', '$window', function($scope, UserService,$window,$location) {
alert("inside user controller");
var self = this;
$scope.user={};
$scope.user.userName="murali";
$scope.user.password="murali123";
$scope.getUser = function(user){
alert("inside function");
UserService.getUser(user).then(function(data){
alert("data::"+JSON.stringify(data.userName));
$window.location.href ='/welcome';
});
};
}]);
App.controller('UserController2', ['$scope', 'UserService', function($scope, UserService) {
alert("inside user controller");
$scope.user={};
$scope.findUser = function(){
alert("inside function");
$scope.user = UserService.findUser();
alert("userName::"+$scope.user.userName);
};
}]);
userservice.js
App.factory('UserService', ['$http', '$q', function($http, $q){
var user = {};
return {
getUser : function(user){
return $http.post('http://localhost:8080/user/login', angular.toJson(user))
.then(
function(response){
alert(JSON.stringify(response.data));
user=response.data;
return response.data;
},
function(errResponse){
console.error('Error while getting response');
return $q.reject(errResponse);
}
);
},
shareUser : function(){
return user;
}
};
}]);
If you redirect the entire page is reloaded and the service is created from 0, no data is saved, unless you store it in cookie or local/session storage. But I see you are using angular-route, so, you can still get it done.
First, when using angular-route, the views does not need to be a full html doc and instead just a piece of it. Example:
index.html
<!DOCTYPE html>
<html>
<head>
<base href="/">
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"> </script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular-route.js"></script>
<script src="app.js"></script>
<script src="usercontroller.js"></script>
<script src="userservice.js"></script>
</head>
<body>
<div ng-app="myApp">
<ng-view></ng-view> <!-- Required by angular-route -->
</div>
</body>
</html>
Please, note the <ng-view></ng-view> element, it is required by angular-route and is where the views will be loaded.
data.html
<form>
<input type="text" name="Name" ng-model="user.userName"> Name <br/>
<input type="text" name="password" ng-model="user.password"> Password <br/>
<button type="submit" ng-click="getUser(user)" >Submit</button>
</form>
data2.html
<form>
<input type="text" name="Name" ng-model="user.userName"> Name <br/>
<input type="text" name="password" ng-model="user.password"> Password <br/>
<button type="submit" ng-click="findUser()" >Submit</button>
</form>
Note that in data2.html I changed ng-click="shareUser()" to ng-click="findUser()" as UserController2 does not have a shareUser function.
Now, in UserController instead of using window.location.href ='/welcome'; use $location.path('/welcome');, this is what you need to use to navigate without reloading the entire page, angular-route will do the magic. You will need to add the $location service as a dependency.
In UserController2, change UserService.findUser(); to UserService.shareUser(); because UserService does not have a findUser function, and I think shareUser is what you are trying to use.
Also, take a look again to the $routeProvider configuration, '/data2.html' might be pointing to the wrong location.
And you are ready, reload the page and happy coding.
Related
<form class="" ng-submit="submit()" ng-controller="MailingListController">
<input class="form-element large" placeholder="Email address" ng-model="emailaddress">
<input class="form-submit button large bkg-charcoal bkg-hover-pink color-white color-hover-white" type="submit" id="submit" value="Submit">
</form>
<script>
angular.module('ComingSoon', [])
.controller('MailingListController', ['$scope', function($scope) {
console.log("Working");
$scope.submit = function() {
console.log($scope.emailaddress);
};
}]);
</script>
I have tried to submit this form and the logs is showing there is nothing inside $scope.emailaddress. I have followed the documentation from angular website but it still doesn't work. Where isit that i am doing it wrongly?
Controller Binding to the view May gone wrong . you can take a look
here in the following plnkr
html :-
<!DOCTYPE html>
<html ng-app="ComingSoon">
<head>
<link rel="stylesheet" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body ng-controller="MailingListController">
<form class="" ng-submit="submit()">
<input class="form-element large" placeholder="Email address" ng-model="emailaddress">
<input class="form-submit button large bkg-charcoal bkg-hover-pink color-white color-hover-white" type="submit" id="submit" value="Submit">
</form>
</body>
</html>
controller :-
angular.module('ComingSoon', [])
.controller('MailingListController', ['$scope', function($scope) {
console.log("Working");
$scope.submit = function() {
console.log($scope.emailaddress);
};
}]);
Check you console while doing !!
https://plnkr.co/edit/B7aJhGKhXin1tsldljpz?p=preview
hi it is working for me
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
<script src="Scripts/angular.js"></script>
<script>
angular.module('ComingSoon', [])
.controller('MailingListController', ['$scope', function ($scope) {
console.log("Working");
$scope.submit = function () {
console.log($scope.emailaddress);
};
}]);
</script>
</head>
<body ng-app="ComingSoon">
<form class="" ng-submit="submit()" ng-controller="MailingListController">
<input class="form-element large" placeholder="Email address" ng-model="emailaddress">
<input class="form-submit button large bkg-charcoal bkg-hover-pink color-white color-hover-white" type="submit" id="submit" value="Submit">
</form>
</body>
</html>
I get an injector:modulerr error in a basic MEAN app...
Here is my home.html:
<!DOCTYPE html>
<html ng-app="jobs">
<head>
<title>GA Jobs</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.10/angular-ui-router.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"/>
<link rel='stylesheet' href='/stylesheets/style.css' />
<script src="/javascripts/main.js"></script>
</head>
<body>
<div class="time-slot" ng-controller="JobsController">
<form class="form-inline" role="form" action="/upload" method="/post">
<select>
<option value="hit_list">Hit List</option>
<option value="contact">Contact</option>
<option value="engagement">Engagement</option>
<option value="hired">Hired</option>
</select>
<input type="text" ng-model="company" class="form-control" name="company" id="company" placeholder="Company">
<input type="text" ng-model="contact" class="form-control" name="contact" id="contact" placeholder="Contact">
<button type="button" class="btn btn-default">Add</button>
</form>
<h1>this is home.html</h1>
<h1>{{company}}</h1>
<h1>{{contact}}</h1>
</div>
</body>
</html>
here is my main.js:
var app = angular.module('jobs',['ngRoute'])
app.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'home.html',
controller: 'JobsController'
})
})
app.controller('JobsController',
function($scope, $stateParams, posts){
});
Does this have something to do with having a server-router as well and ejs files in the view? I'm confused on how the client-side angular router works with the node server-side router. please help.
The app is unable to load the ngRoute module. ngRoute has been moved to its own module and is no longer part of the core.
You'll need to include the angular-route module to use ngRoute. You should replace this line:
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.10/angular-ui-router.js"></script>
with this:
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular-route.min.js"></script>
I am using a form in html, using angular, and binding the username and email id of the user.
I wish to display the details of the particular user onto a server page, where in when a user clicks on Submit details on the front end, the data is "binded" and the information is simultaneously shown on the server page.
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<link href='https://fonts.googleapis.com/css?family=Lobster' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
<title>Random title here</title>
<body ng-app="test" ng-controller="mainctrl as ctrl">
<div class="container">
<div class="col-sm-8 col-sm-offset-2">
<form name="userform" ng-submit="ctrl.submit()">
<div class="form-group">
<label> Name</label>
<input type="text" name="name" class="form-ctrl" ng-model="ctrl.user.name">
</div>
<div class="form-group">
<label> Email id</label>
<input type="email" name="email" class="form-ctrl" ng-model="user.email">
</div>
<button type="submit" class="btn btn-primary"> Submit </button>
</form>
</div>
</div>
<script>
var test=angular.module('test',[]);
test.controller('mainctrl',[function($scope,$html){
$scope.user={};
$scope.submit= function () {
$http({
method : 'POST',
url : 'test1.java', //No idea what to put here. Help pls.
data : $scope.user;
headers : {'Content-Type':'application/x-www-form-urlencoded'}
}).success(function(data)
{
console.log("Success");
});
}
}]);
</script>
</body>
</html>
This is just a sample of code I typed. As a beginner, any help would be appreciated. Thanks.
If you are using controller as syntax than you should write your function with reference this. Your controller snippet would be like
angular.module('test',[])
.controller('mainctrl',[function($scope, $http){
var cm = this;
cm.user={};
cm.submit= function () {
$http({
method : 'POST',
url : form.attributes['target'],
data : cm.user;
}).success(function(data)
{
console.log("Success");
});
}
}]);
and pass the form element in your ng-submit directive. Like
<form name="userform" ng-submit="ctrl.submit($element.action)">
I hope my code will be usefull for you!
View:
<body ng-controller="UserDataController">
<form ng-submit="sendData(user)">
<input type="text" placeholder="name" ng-model="user.name" />
<input type="text" placeholder="second name" ng-model="user.second_name" />
<button type="submit" class="btn btn-sm btn-primary">
Save
</button>
</form >
Cotroller:
angular.module('httpExample', [])
.controller('UserDataController', ['$scope', '$http', function($scope, $http) {
$scope.user = {};
$scope.sendData= function(user) {
$http.post("/SomeUrl", user).success(function(data, status) {
console.log(data);
console.log(status);
$scope.data = data;
// now you can write {{data}} at your veiw
// example {{data.id}}
});
}]);
Example: get request
We are using angular to do like/unlike behavior for our app.
Code for html
<html>
<body ng-app="myApp">
<div ng-controller="newsCntrl" >
<form ng-submit="post()" name="postForm" id="postForm" >
<input type="submit" id="submit" value="Submit"/>
</form>
Like</span>
</div>
</body>
</html>
Code for controller
myApp.controller("newsFeedCtrl", function ($scope, $http) {
console.log("inside newsFeedCtrl");
$scope.post() = function() {
console.log("posting");
}
$scope.likePost = function(postId) {
console.log("liking post");
}
});
The problem is when we click on like; it also calls post function which should not be happening.
Are we missing anything here?
There is a mismatch between the controller name in the HTML:
<div ng-controller="newsCntrl" >
and the controller in the JS:
myApp.controller("newsFeedCtrl", function ($scope, $http)
If I fix it, it seems to work.
Check this fiddle
You should remove syntax error
Code for html:
<html>
<body ng-app="myApp">
<div ng-controller="newsCntrl">
<form ng-submit="submitPost()" name="postForm" id="postForm">
<input type="submit" id="submit" value="Submit"/>
</form>
Like
</div>
</body>
</html>
Code for controller:
myApp.controller("newsFeedCtrl", function ($scope, $http) {
console.log("inside newsFeedCtrl");
$scope.submitPost = function() {
console.log("posting");
}
$scope.likePost = function(postId) {
console.log("liking post");
}
});
I am trying to learn angular so forgive my stupid mistakes and ignorance. That being said,
I add data to my scope when I create my controller ProducerCtrl. This works before I add anything else. When I add the addname function it breaks my data fetch. I am sure I am doing something wrong because I don't know what I am doing. I would like to have these
two bits of code work. Maybe I need to move one or both to another area.
<html><head>
<title></title>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.1/angular.min.js"></script>
<script>
var eventApp = angular.module('eventApp', []);
var szAction = "/GoGetData";
var szAction2 = "/GoPostData" })";
eventApp.controller('ProducerCtrl', ['$scope', '$http', function (scope, http) {
http.get(szAction).success(function (data) {
scope.producer = data;
});
$scope.addName = function () {
http.post(szAction2, scope.producer);
};
}]);
</script>
</head>
<body>
<div ng-app="eventApp">
<div ng-controller="ProducerCtrl">
Name:<input ng-model="producer.Name" type="text" /><br>
Hello {{producer.Name}}
<form ng-submit="addName()">
<input ng-model="producer.Name" type="text">
<input type="submit" value="add">
</form>
</div>
</div>
</body></html>
I've made some changes on your code. When you click on add will prompt an alert.
Your HTML:
<body>
<div ng-app="eventApp">
<div ng-controller="ProducerCtrl">
Name:<input ng-model="producer.Name" type="text" /><br />
Hello {{producer.Name}}
<form ng-submit="addName()">
<input ng-model="producer.Name" type="text" />
<input type="submit" value="add" />
</form>
</div>
</div>
<body>
Your Angular code:
var eventApp = angular.module('eventApp', []);
eventApp.controller('ProducerCtrl', ['$scope', '$http', function ($scope, $http) {
$scope.producer = { Name : '' };
$scope.addName = function () {
alert($scope.producer.Name);
};
}]);
See here.
Take a look here to check $http.