I am trying to implement a simple $http post with angular within this controller.
app.controller('LoginCtrl',['$scope','admin','$http',function($scope,$http,admin){
$scope.isAdmin = admin.isAdmin;
$scope.logout = admin.logout;
$scope.login = function(){
if(!$scope.username || !$scope.password ){ return; }
$http.post('/login',{ username: $scope.username, password: $scope.password });
$scope.username = '';
$scope.password = '';
};
}]);
This part
$http.post('/login',{ username: $scope.username, password: $scope.password });
is throwing this error
TypeError: undefined is not a function
at l.$scope.login (http://localhost:3000/javascripts/angularApp.js:165:9)
at hb.functionCall (http://ajax.googleapis.com/ajax/libs/angularjs/1.3.10/angular.min.js:198:426)
at Cc.(anonymous function).compile.d.on.f (http://ajax.googleapis.com/ajax/libs/angularjs/1.3.10/angular.min.js:214:485)
at l.$get.l.$eval (http://ajax.googleapis.com/ajax/libs/angularjs/1.3.10/angular.min.js:126:193)
at l.$get.l.$apply (http://ajax.googleapis.com/ajax/libs/angularjs/1.3.10/angular.min.js:126:419)
at HTMLFormElement.<anonymous> (http://ajax.googleapis.com/ajax/libs/angularjs/1.3.10/angular.min.js:215:36)
at HTMLFormElement.c (http://ajax.googleapis.com/ajax/libs/angularjs/1.3.10/angular.min.js:32:363)
here is the HTML for the ui-view.
<script type="text/ng-template" id="/login.html">
<button id="logout" class="btn btn-default" ng-click="logout()" ng-show="isAdmin()">Log Out</button>
<div ng-controller="LoginCtrl">
<form id="login" ng-submit="login()">
<h2>The Login Page.</h2>
<label>Username:</label>
<input type="text" ng-model="username" placeholder="username"/>
<label>Password:</label>
<input type="password" ng-model="password" placeholder="password"/>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</script>
I have checked the syntax, everything looks correct, $http is being recognized as an object when I console.log it within the controllers scope.Yet for some reason I cannot make this post request because an error is being thrown. I am using expressjs to serve the content, and my current route for '/login' is just a simple response.send('response sent!'). As you can see in the HTML I am using angular ui-router, in which I also have a .state set for it, if this needs to be provided please let me know.
I have been frustrated about this because this is clearly known function, and I cannot find any resources online to help me with the exact problem. I have tried setting the content type in the headers, and other online solutions but nothing has been helping. It seems like it may be something stupid, but I can't find it.
I would appreciate any input or help, thank you.
Dependency injection order is wrong
app.controller('LoginCtrl', ['$scope', 'admin', '$http',function($scope, $http, admin) { ...
should be
app.controller('LoginCtrl', ['$scope', '$http', 'admin', function($scope, $http, admin) { ...
Related
I am getting an unknown provider error. My structure is set up with two different files, a controller file and a service file. For some reason the angular app cannot find the service? If I put the service within the same file it works fine?
controller file:
(function() {
'use strict'
angular
.module('poke', ['ngResource'])
.controller("appController", appController)
appController.$inject = ['$scope', 'user']
function appController($scope, user){
$scope.saveUser = saveUser;
// getProducts();
//
function saveUser(user_email) {
return user.save({user_email}, function(data) {
$scope.email = []
});
}
}
})()
service file
(function() {
angular
.module('poke')
.factory("user", user)
user.$inject = ['$resource']
function user($resource) {
return $resource("/users",{}, {})
}
})();
html
<body ng-app="poke" ng-controller="appController" ng-cloak>
<div class="page-header">
<h1>Pokemon Go!</h1>
</div>
<form ng-submit="saveUser(email)" style="margin-top:30px;">
<h3>Please enter your email address to receive news about Pokemon Go in your city!</h3>
<input type="text" class="form-control" placeholder="example#email.com" ng-model="email"></input>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</body>
Keep your main Module independently by injecting the global Dependencies. So you no need to refer this dependency in all files.
angular.module('myModule', ['ngResource']);
angular
.module('poke')
.controller("appController", appController)
then you can use $resource dependency across your angular components
Hope this helps
I am pretty new to Node.js, Express and angularjs. I am working on a simple Sign-in functionality that will redirect to another page if sign in success. I know I can use window.location for the redirect purpose, but I am trying to use res.render because I also want to pass some values to the new page.
However, the res.render doesn't seem to work, the result page never shows up.
Signin.ejs:
<div id="navbar" class="navbar-collapse collapse" ng-controller="signinController">
<form class="navbar-form navbar-right">
<div class="form-group">
<input type="email" ng-model="inputEmail" placeholder="Email" class="form-control">
</div>
<div class="form-group">
<input type="password" ng-model="inputPassword" placeholder="Password" class="form-control">
</div>
<button type="submit" ng-click="signIn()" class="btn btn-success">Sign in</button>
</form>
</div>
The javascript embedded is:
function signinController($scope,$http,$location) {
$scope.signIn = function() {
$http({
method: 'POST',
url: '/signin',
data: { "inputEmail": $scope.inputEmail, "inputPassword": $scope.inputPassword }
});
};
}
app.js
app.get('/result', home.result);
app.post('/signin', home.afterSignIn);
The home.js
function afterSignIn(req,res)
{
// check user already exists
var sqlStr="select * from users where email='"+req.param("inputEmail")+"' and password='"+req.param("inputPassword")+"'";
console.log("Query is:"+sqlStr);
res.render('result', { result: 'sqlStr' });
}
exports.result=function(req,res){
res.render('result');
}
exports.afterSignIn = afterSignIn;
result.ejs
<%= result %>
Any suggestions or working examples are highly appreciated :)
I think you are bit confused. Use express as the REST engine when it comes to routes. Angular routes will take care of the display logic and view routing on the client side.
I would suggest you to pass JSON data to front end angular and let it do the job for you. For example:
app.get('/', function (req, res) {
res.json({
title : "n562d",
strapline : "Please Log In"
})
});
You can access the API at the endpoint: http://localhost:3000/ Use $resource services to access the express endpoint.
example:
var MyResource = $resource('/');
var myResource = new MyResource();
myResource.$get(function(result){
//result holds -->{title : "n562d", strapline : "Please Log In"}
//use $location to change the uri, which is handled by Angular route config
$location.path('/')
});
For angular routing,i would suggest you to use ui-router.
example:
function($stateProvider,$urlRouterProvider){
$urlRouterProvider.otherwise("/");
$stateProvider
.state('index', {
url: "/",
templateUrl: 'app/authorization/index.tpl.html',
controller: 'AuthController'
})
.state('login', {
url: "/login/",
templateUrl: 'app/authorization/login.tpl.html',
controller: 'AuthController'
})
.state('signup',{
url: "/signup/",
templateUrl : 'app/authorization/signup.tpl.html',
controller: 'AuthController'
});
}
]);
Let me know if you need more detailed answer then i will update it. I hope it helps.
Feel free to look for similar implementation here.
My setup is NodeJS, MongoDB, and Angular. I'm currently trying to add POSTing capability to my test code but can't quite wrap my head around it. Currently I can pull data from the DB and I threw together a quick and dirty form/factory based on a number of examples I've seen to try to get the POST function working.
The problem I'm running into is actually getting the values to be added to the DB. When I submit the form, a new ObjectID is created in the DB with a "_v" field and a value of 0. So I know the POST is at least being sent to the DB, but the values I want are not. I'm sure I'm doing something stupid and any help is greatly appreciated.
Here is my controller/factory setup: (I named the POST factory "taco" so it would stand out. Also because they're delicious.)
angular.module('app', ['ngRoute'])
.factory('Users', ['$http', function($http) {
return $http.get('/users');
}])
.factory('taco', ['$http', function($http) {
return $http.post('/users');
}])
.controller('UserController', ['$scope', 'Users', function($scope, Users) {
Users.success(function(data) {
$scope.users = data;
}).error(function(data, error) {
console.log(error);
$scope.users = [];
});
}])
.controller('ExampleController', ['$scope', 'taco', function($scope, taco) {
$scope.submit = function() {
if ($scope.users.name) {
$scope.name.post(this.name);
$scope.name = '';
}
};
}]);
Here is my form:
<div>
<form ng-submit="submit()" ng-controller="ExampleController">
Enter the things:<br/>
<input type="text" ng-model="name" name="user.name" placeholder="name" /><br/>
<input type="text" ng-model="emp_id" name="user.emp_id" placeholder="EID" /><br/>
<input type="text" ng-model="loc" name="user.loc" placeholder="location" /><br/>
<input type="submit" id="submit" value="Submit" />
</form>
</div>
To post using the $http service you can do:
angular.module('myApp')
.controller('MyController', function($scope, $http) {
$http.post('/destination', {my: 'data'});
});
You're not sending any data in your POST request. The taco service just executes a $http.post call and returns the promise.
Please look at the $http service documents: https://docs.angularjs.org/api/ng/service/$http
I would define a function submit that would send the data once a user clicks on submit:
$scope.submit = function() {
$http.post('/destination', {my: 'data'});
}
I'm writing a HTML web app using Ionic. While trying to bind an input element to a $scope var, I'm getting undefined.
SignupCtrl.js:
angular.module('SUSU.controllers', [])
.controller('SignupCtrl',
function ($scope) {
/* Form entries */
$scope.signupForm = {
email: "",
emailConfirm: ""
};
});
signup.html:
<label class="item item-input">
<input type="email" placeholder="Email" ng-model="signupForm.email">
</label>
app.js:
angular.module('SUSU', ['ionic','SUSU.controllers'])
.config(function ($stateProvider, $urlRouterProvider) {
// Set and define states
$stateProvider
....
.state('tabs.signup', {
url: '/signup',
views: {
'login-tab': {
templateUrl: 'templates/signup.html',
controller: 'SignupCtrl'
}
}
});
While debugging I have noticed that the value of signupForm.email is undefined after inserting text to the email input. How can I bind those two and what am I doing wrong?
Guys I can't believe I have wasted so much time about that...
It's the type="email" who caused the problem. Because of some reason it doesn't work. When I changed it to type="text" it worked fluently.
Read more
There may be a better way to do this, but one way to achieve what you want is to do the following:
In your signup.html add a ng-change to your input:
<label class="item item-input">
<input type="email" placeholder="Email" ng-model="signupFormEmail" ng-change="updateEmail(signupFormEmail)">
</label>
Then in your controller add a method to $scope that will update your signupForm email property:
$scope.updateEmail = function(email){
$scope.signupForm.email = email;
}
I'm very new to Angular and am try to make a simple "Hello World" webservice call to a simple Rest web service that I've verified returns "Hello World" when you hit it.
I have 3 alerts in the method. I see the "In method" alert and then don't see any of the other alerts. I've attached fiddler and the web service request is never made. I've got to be overlooking something basic here I would think....any ideas on what am I may be missing?
Fiddler shows that the web service call is successful and I can see the results from the Web Service I expect but using Chrome's developer tools shows me that the call to the service is being cancelled by something inside of Angular.
Thanks in advance to any help provided.
(function () {
var app = angular.module("loginApp", ['ngResource'])
.config(function ($httpProvider) {
// Enable CORS
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
});
app.controller('LoginController', function ($scope, $http) {
this.loginImage = "images/ActiveView_ContentMgm_140x40.png";
this.loginUser = function () {
var token = "";
var loginUrl = "http://ten1.com/services/rest/demoservice.svc/Login";
delete $http.defaults.headers.common['X-Requested-With'];
var result = $http({ method: 'GET', url: loginUrl, params: { userName: this.userName, passWord: this.passWord } })
.success(function (data, status) {
$scope.status = status;
$scope.data = data;
})
.error(function (data, status) {
$scope.data = data || "Request failed";
$scope.status = status;
});
token = data.Token;
};
});
})();
UPDATE:
Right now I'm clicking the submit button on a login form and just attempting to get back a string so I can verify basic communication with the web service. My goal is to pass the username/password in and get a token back. Here's the form:
<form ng-submit="loginCtrl.loginUser()" novalidate>
<div class="form-group">
<label for="exampleInputEmail1">Username</label>
<input type="text" class="form-control" style="border-radius:0px" ng-model="loginCtrl.loginForm.userName" placeholder="Enter username">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password </label>
<input type="password" class="form-control" style="border-radius:0px" ng-model="loginCtrl.loginForm.passWord" placeholder="Password">
</div>
<button type="submit" class="btn btn-sm btn-default">Log in</button>
Inject $scope and $http into your controller, not in your loginUser() function:
app.controller('LoginController', function ($scope, $http) {
I found that the service I was hitting was returning a "No 'Access-Control-Allow-Origin' " message which would allow the service to complete but would cause Angular to short circuit. I fixed this by adding an "Access-Control-Allow-Origin" to the Response header in the service.
Links:
Cross Origin Resource Sharing for c# WCF Restful web service hosted as Windows service
"Access-Control-Allow-Origin:*" has no influence in REST Web Service