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;
}
Related
While working on a project in ionic i noticed my two data-binding bugging out.
I really can't get my head around why this is the case.
I tried making a new ionic project with "ionic start myApp sidemenu" to test out the data binding, and even in the new project it is not working. Am i the one doing something wrong or is this just really bugging out?
Link to the working databinding example i'm following
As you can see in that example, when you fill in the input fields: first name, last name AND full name gets update. When i add this code to an ionic project, only the first/last name get updated, but the full name doesn't get updated and stay on the values initialized in the controller.
It look likes the $scope.firstName and $scope.lastName don't get 'live updated' in the controller but only in the view for some reason.
If i try to console log the $scope.firstName after i filled in the input field, it still returns 'john' (the initial value) and not the value i filled in.
Code in ionic:
html
<ion-view view-title="Search">
<ion-content>
<strong>First name:</strong> {{firstName}}<br />
<strong>Last name:</strong> <span ng-bind="lastName"></span><br />
<strong>Full name:</strong> {{getFullName()}}<br />
<br />
<label>Set the first name: <input type="text" ng-model="firstName"/></label><br />
<label>Set the last name: <input type="text" ng-model="lastName"/></label>
</ion-content>
</ion-view>
controller:
angular.module('starter.controllers', [])
.controller('SearchCtrl', function($scope) {
// Initialize the model variables
$scope.firstName = "John";
$scope.lastName = "Doe";
// Define utility functions
$scope.getFullName = function ()
{
return $scope.firstName + " " + $scope.lastName;
};
})
routing:
angular.module('starter', ['ionic', 'starter.controllers'])
.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('app', {
url: '/app',
abstract: true,
templateUrl: 'templates/menu.html',
controller: 'AppCtrl'
})
.state('app.search', {
url: '/search',
views: {
'menuContent': {
templateUrl: 'templates/search.html',
controller: 'SearchCtrl'
}
}
})
You should use ng-bind. From AngularDocs
The ngBind attribute tells AngularJS to replace the text content of
the specified HTML element with the value of a given expression, and
to update the text content when the value of that expression changes
replace
<strong>Full name:</strong> {{getFullName()}}<br />
with
<strong>Full name:</strong> <span ng-bind="getFullName()"></span><br />
Here I am Trying to Login with user credientials
if user is valid , I want to pass UserName,LastloginTime,Role values to another page using angular js
<form role="form" ng-app="MyApp" ng-controller="MasterController">
<div class="form-group">
<label>
Username</label>
<input type="text" class="form-control" placeholder="Username" required ng-model="username" />
</div>
<div class="form-group">
<label>
Password</label>
<input type="password" class="form-control" placeholder="Password" required ng-model="password" />
</div>
<div class="checkbox">
<label>
<input type="checkbox" ng-model="remember">
Remember my Password
</label>
</div>
<input type="button" value="Submit" ng-click="GetData()" class="btn btn-danger" />
<%--<button type="button" class="btn btn-danger" ng-click="GetData()">Submit</button>--%>
<span ng-bind="Message"></span>
</form>
js file here
$scope.GetData = function () {
debugger;
var data = { UserName: $scope.username, Password: $scope.password };
$http.post("api/Test/CheckUsername", data)
.success(function (data, status, headers, config) {
if (data != "") {
$scope.Employees = data;
window.location.href = "EmployeeMaster";
//$scope.Reporting = data;
}
else {
alert("Invalid Credientials");
}
});
}
I want to display values in a master page
<table class="table">
<tr ng-repeat="Emp in Employees">
<th>User </th>
<td>:</td>
<td>{{Emp.username}}</td>
</tr>
<tr>
<th>Designation </th>
<td>:</td>
<td>{{Emp.RoleName}}</td>
</tr>
<tr>
<th>Last Login </th>
<td>:</td>
<td>{{Emp.LastLogin}}</td>
</tr>
</table>
How can i pass the values login page to Home page?
I suggest creating a service to store your global data:
myApp.factory('DataService', function() {
var user = {
name: '',
role: ''
// and so on
};
return {
user: user
};
});
Just inject this to all your controllers and set and retrieve the data you need:
myApp.controller('MyCtrl', function($scope, DataService) {
// make your DataService available in your scope
$scope.DataService = DataService;
});
This lets you bind models globally to the DataService.
Check out angular-storage A Storage done right for AngularJS. It is great for storing user info/tokens/ any object.
Key Features
Uses localStorage or sessionStorage by default but if it's not available, it uses ngCookies.
Lets you save JS Objects
If you save a Number, you get a Number, not a String
Uses a caching system so that if you already have a value, it won't get it from the store again.
https://github.com/auth0/angular-storage
There is lot of ways of to achieve this
1) Use $rootscope like you use $scope like
$rootscope.userName = ""
Inject the $rootscope dependency in the controller where you want to show it and create an object name Employee and fill it with $rootscope.
2) use constant like
module.constant("userData", data);
Inject the userData dependency in the controller where you want to show it and create an object name Employee and fill it with userData.
3) You can use service/factory and save the data in localstorage/sessionstorage
to transfer data between pages, you can use stateParams:
in the routes file:
$stateProvider
.state('employeeMasterState', {
url: '/employeeMasterUrl/:employeeData',
templateUrl: 'info/employeeMaster.tpl.html',
controller: 'employeeMasterCtrl',
controllerAs: 'employeeMasterCtrlAs'
});
js:
$scope.GetData = function () {
debugger;
var data = { UserName: $scope.username, Password: $scope.password };
$http.post("api/Test/CheckUsername", data)
.success(function (data, status, headers, config) {
if (data != "") {
this.state.go('employeeMasterState',{employeeData:data});
}
else {
alert("Invalid Credientials");
}
});
}
in the next page js:
constructor($scope, $statePArams){
$scope.empData = $stateParams.data;
}
You can create a service or a factory to share data between webpages. Here is the documentation
So I have the code for a search bar in its own template, which I have in a custom directive. Then I put that directive in the my Navbar template.
<form class="navbar-form navbar-left" role="search">
<div class="form-group">
<input type="text" class="form-control" placeholder="Search" ng-model="searchText">
</div>
<button type="submit" class="btn btn-default" ng-click="go('/searchResults')">Submit</button>
</form>
.
.state('searchResults', {
url: '/searchResults',
templateUrl: 'templates/searchResults.html',
controller: 'searchController'
})
}]).
directive('searchBar', function() {
return {
restrict: 'E',
templateUrl: 'templates/search.html',
controller: "searchController"
}
});
My SearchController handles the scope for this search bar, but I'm having some trouble binding data to another template, which is my searchResults template. My SearchController calls on a service I wrote which retrieves some data and works fine. When I try to bind the data to my SearchResults page however, angular does not bind any of the data received from the service, (it will console log out the correct data though).
Name: {{player.playerName}}<br>
Link: {{player.link}}<br>
Things: {{things}}<br>
controller:
angular
.module('app')
.controller('searchController', ['$scope',"$http","$location", "PlayerDAO", function($scope, $http, $location, PlayerDAO){
$scope.things="stuff";
$scope.go = function ( path ) {
if(checkSearchBar()){
$location.path( path );
PlayerDAO.getPlayers($scope.searchText).then($scope.postPlayerToResultsPage, onError);
}
};
$scope.postPlayerToResultsPage=function(result){
$scope.player=result;
$scope.things="Hooray, it worked";
$scope.player.playerName;
console.log(result);
};
}]);
Oddly enough to me however, it will bind any data that is not in the function I use to get the data (i.e. it will bind {{things}}), but any of the data in my function "postPlayerToResultsPage", isn't seen by Angular. If I take the code for the search bar and put it in my search results page directly, the nav-bar that appears on that page works flawlessly, however I need the search-bar to be on my main navigation template, view-able on all pages.
I suspect your data isn't binding due to the prototypical nature of your directive's $scope.
Try using controllerAs syntax for data binding to avoid $scope ambiguity. e.g.
directive:
controller: 'searchController',
controllerAs: 'searchCtl'
controller:
var controller = this;
$scope.postPlayerToResultsPage=function(result){
controller.player=result;
controller.things="Hooray, it worked";
controller.player.playerName;
console.log(result);
};
html:
Name: {{searchCtl.player.playerName}}<br>
Link: {{searchCtl.player.link}}<br>
Things: {{searchCtl.things}}<br>
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) { ...
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.