Assigning controller to a form template with $routeProvider in AngularJS - javascript

I'm building my first angular app, starting with a simple login form. I load the form from a partial, however when I try submitting the form, nothing is logged to the console, i.e. I assume my authenticate() method is not called. I have the following definition for my app.js:
'use strict';
angular.module('spForums',[])
.config(['$routeProvider','$locationProvider',function($routeProvider,$locationProvider) {
$routeProvider.when('/login', {
templateUrl: 'static/partials/login.html',
controller: loginController,
controllerAs: 'login'
});
$locationProvider.html5Mode(true);
}])
And here's the controller, defined in a separate controller.js:
'use strict';
function loginController() {
this.email = '';
this.password = '';
this.authenticate = function () {
console.log(this.email);
console.log(this.password);
};
};
Here's the partial, login.html:
<form class="form-signin" novalidate ng-submit="login.authenticate()">
<h2 class="form-signin-heading">Please sign in</h2>
<label for="inputEmail" class="sr-only">Email address</label>
<input type="email" id="inputEmail" class="form-control" placeholder="Email address" required autofocus ng-model="login.email">
<label for="inputPassword" class="sr-only">Password</label>
<input type="password" ng-model="login.password" id="inputPassword" class="form-control" placeholder="Password" required>
<div class="checkbox">
<label>
<input type="checkbox" value="remember-me"> Remember me
</label>
</div>
<input class="btn btn-primary" type="submit" value="Sign-in">
</form>
And here's the relevant part of index.html, or in my case, forum.html that includes the partial:
<!doctype html>
<html lang="en" ng-app="spForums">
<head>
<script type="text/javascript" src="/static/js/lib/angular.min.js"></script>
<script type="text/javascript" src="/static/js/lib/angular-resource.min.js"></script>
</head>
<body>
<div class="container" id="forumcontainer" ng-view>
</div> <!-- /container -->
<script type="text/javascript" src="/static/js/app.js"></script>
<script type="text/javascript" src="/static/js/controller.js"></script>
</body>
</html>
I'd like to end this by saying I'm new to Angular-JS. As in I just saw a bunch of tutorials and this is my first app. Please tell me where I'm wrong.
EDIT:- I'm using Angular-JS version 1.0.7.

You need to include ngRoute module into your application, it's not shipped by default:
<head>
<script>document.write('<base href="' + document.location + '" />');</script>
<script src="/static/js/lib/angular.min.js"></script>
<script src="/static/js/lib/angular-route.min.js"></script>
<script src="/static/js/lib/angular-resource.min.js"></script>
</head>
Note, that you also need to define base href tag, since you are using HTML5 mode.
Then define module with necessary dependencies:
angular.module('spForums', ['ngRoute', 'ngResource'])

Related

Angularjs ngRoute is not working

i have an index page(login ) in which register link is present so while redirecting i am trying to load the controller but it is not loading also there is no error in console.
My home page is getting loaded with URL : http://localhost:8081/WebServices/
and after clicking resgiter i am trying to rediect it to : http://localhost:8081/WebServices/#/regsiter
Help would be appreciated.
My index.html page
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Login Page</title>
<script type="text/javascript" src= "/WebServices/js/angular.min.js"></script>
<script type="text/javascript" src= "/WebServices/js/angular-resource.min.js"></script>
<script type="text/javascript" src= "/WebServices/js/angular-route.min.js"></script>
<script type="text/javascript" src= "/WebServices/js/friendsCtrl.js"></script>
<script type="text/javascript" src= "/WebServices/js/friendsService.js"></script>
<script type="text/javascript" src= "/WebServices/js/loginCtrl.js"></script>
<link rel="stylesheet" type="text/css" href="./css/bootstrap.min.css">
</head>
<body>
<div ng-app="loginApp">
<div class="col-md-3">
<h2>Login</h2>
<form name="loginform" role="loginform" ng-submit="login()">
<div class="form-group" ng-class="{ 'has-error':loginform.username.$dirty && loginform.username.$error.required }" >
<label for="username">Username</label>
<input type="text" name="username" class="form-control" ng-model="user.username" required />
<span ng-show="loginform.username.$dirty && loginform.username.$error.required " class="help-block">Username is required</span>
</div>
<div class="form-group" ng-class="{ 'has-error':loginform.username.$dirty && loginform.username.$error.required }">
<label for="Password">Password</label>
<input type="password" name="password" class="form-control" ng-model="user.password" required />
<span ng-show="loginform.password.$dirty && loginform.password.$error.required " class="help-block">Password is required</span>
</div>
<div class="form-actions">
<button type ="submit" class="btn btn-primary" ng-disabled="loginform.$invalid">Login</button>
Resgiter
</div>
</form>
</div>
</div>
</body>
</html>
loginCtrl.js file
var loginApp=angular.module('loginApp',['ngRoute']);
loginApp.config(['$routeProvider', function($routeProvider){
$routeProvider
.when('/' , {
templateUrl:'index.html',
controller: 'loginCtrl'
})
.when('/regsiter' , {
templateUrl:'registration_ang.html',
controller: 'loginCtrl'
})
.otherwise({
redirectTo:'/'
});
}]);
loginApp.controller('loginCtrl',['$scope',function($scope){
console.log("controller loaded");
alert("controller loaded");
$scope.login=function(){
console.log("inside loginCtrl : login function");
alert("checking login.");
};
}
]
);
You have missed to add ng-view directive on your page, so that will load the template & controller configured on $routeProvider inside ng-view directive element.
<div ng-view></div>

AngularJS "Controller as" in templates

I am new to AngularJS world and I am trying to setup a basic laravel/angular JWT auth following this tutorial.
What I'd like to do, it's to use the "Controller As" syntax instead of the $scope as stated in the tutorial. For now, here what I have:
app.js
var app = angular.module('app', ['ngRoute']);
app.run(function () {});
app.config(function ($routeProvider, $locationProvider) {
$routeProvider.when('/', {
templateUrl: 'js/templates/login.html',
controller: 'LoginController'
});
});
login controller
angular.module('app')
.controller('LoginController', function ($scope) {
this.title='toto';
this.data = {};
this.submit = function () {
console.log(this.data);
};
});
admin view
<!doctype html>
<html lang="en">
<head>
<title>Blog Administration</title>
<!--css-->
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css"/>
<!--js-->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<!--angular-->
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.4/angular.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.4/angular-route.js"></script>
<script src="js/app.js"></script>
<script src="js/controllers/loginController.js"></script>
</head>
<body ng-app="app">
<div id="wrapper">
<div class="container" id="view" ng-view>
</div>
</div>
</body>
</html>
login template
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body ng-controller="LoginController as login">
<div class="container">
<div id="login" class="col-md-4 col-md-offset-4">
<div id="login-form">
<h4>{{ login.title }}</h4>
<form ng-submit="login.submit()"><!--username-->
<div class="form-group">
<input id="username" type="text" ng-model="login.data.username"/>
</div>
<!--password-->
<div class="form-group">
<input id="password" type="password" ng-model="login.data.password"/>
</div>
<!--submit-->
<div class="form-group">
<button class="btn btn-primary" type="submit">Login</button>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
The problem is that nothing renders. Is it possible to use a controller per template ?
If I put the <ng-controller="LoginController as login"> directive in the view body instead of template everything renders correctly.
Is it a good practice to define a controller per template ? Because the login template should be as generic as possible, so it can be loaded in any view if the user isn't authenticated, that's why I think putting login() action in the controlelr handling the Admin view is wrong.
Can someone advice me on the best practices to have here ?
In order to use controllerAs syntax with routeProvider you need to declare additional property in route configuration:
$routeProvider.when('/', {
templateUrl: 'js/templates/login.html',
controller: 'LoginController',
controllerAs: 'login'
});
Then you need to clean up login template, removing everything but actual template, e.g. no HTML, body tags, etc. You also don't need extra ngController directive in partial template:
<div id="login" class="col-md-4 col-md-offset-4">
<div id="login-form">
<h4>{{ login.title }}</h4>
<form ng-submit="login.submit()">
<!--username-->
<div class="form-group">
<input id="username" type="text" ng-model="login.data.username" />
</div>
<!--password-->
<div class="form-group">
<input id="password" type="password" ng-model="login.data.password" />
</div>
<!--submit-->
<div class="form-group">
<button class="btn btn-primary" type="submit">Login</button>
</div>
</form>
</div>
</div>
Question 1: Is it possible to use a controller per template ?
Ans: Yes. Its very simply. How, is shown in next answer.
Question 2: Is it a good practice to define a controller per template ?
Ans: As per the AngularJs shown rules, Its good practice. Now see the 2
different way of defining the controller for the template.
a. Directly into the template like: <div ng-controller="myCtrl">Whole template
data goes inside this div.</div>
b. from the app.js where we load the template like this:
.state('app.products.all', {
url: '/all',
templateUrl: 'tpl/products/blocks/thumb.html',
controller: 'ProductsAllCtrl'
})
Here i have also shown the controller with the template path. Second way is
more better then the first.

Scripts don't load: Using AngularJS with JSON (Firebase)

I've tried to build an application that let's you input data into several fields, uses AngularJS to put data into a Firebase JSON, and outputs that data into nicely laid out "cards".
Initially I could input and output data, but as soon as I hooked it up to AngularJS and Firebase I just got '{{ 1 + 2 }}' instead of '3' in my browser.
I'm running this code on my webserver, I hope you can help me figure out what the problem is – the page is pretty much blank. Everything that depends on Angular isn't showing up.
Link to live page:
repertoire.me/anustart
Here's my code:
index.html
<html lang="en" ng-app="repertoire">
<head>
<meta charset="utf-8">
<title>Repertoire Beta</title>
<!-- STYLES -->
<link rel="stylesheet" type="text/css" href="assets/css/bootstrap.min.css" />
<!-- SCRIPTS -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.3/angular.min.js"></script>
<script type="text/javascript" src="assets/js/angular.js"></script>
<script type="text/javascript" src="assets/js/angular.min.js"></script>
<script type="text/javascript" src="assets/js/app.js"></script>
<script type="text/javascript" src="assets/js/venues.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body ng-controller="VenueController as venueCtrl">
<p class="ANGULAR_TEST">1 + 2 = {{ 1 + 2 }}</p>
<header class="card">
<h1>repertoire</h1>
</header>
<venue-list></venue-list>
<venue-form></venue-form>
<footer id="info" class="card" ng-include="'footer.html'"></footer>
</body>
</html>
venue-list.html
<section class="card" id="venueList">
<h2 class="venue_name">{{venueCtrl.venue.name}}</h2>
<h3 class="venue_location">{{venueCtrl.venue.location}}</h3>
<div class="pricecat">
<span class="venue_price">{{venueCtrl.venue.price}}</span>
<span class="venue_category">{{venueCtrl.venue.species}} {{venueCtrl.venue.genre}}</span>
</div>
<p class="venue_description">{{venueCtrl.venue.description}}</p>
<p class="venue_tags">{{venueCtrl.venue.tags}}</p>
</section>
venue-form.html
<section class="card" id="venueForm">
<form name="venueForm" ng-controller="VenueController as venueCtrl" ng-submit="venueForm.$valid && venueCtrl.venueForm(info)" novalidate>
<input ng-model="venueCtrl.venue.name" type='text' class="input" id='nameInput' placeholder='Venue Name' required/>
<input ng-model="venueCtrl.venue.location" type='text' class="input" id='locationInput' placeholder='Address' required/>
<select ng-model="venueCtrl.venue.price" type='text' class="input" id='priceInput' ng-options="price for price in [$,$$,$$$,$$$$]">
<option value="">Price</option>
</select>
<input ng-model="venueCtrl.venue.genre" type='text' class="input" id='genreInput' placeholder='Category'/>
<input ng-model="venueCtrl.venue.species" type='text' class="input" id='speciesInput' placeholder='What kind?'/>
<textarea ng-model="venueCtrl.venue.description" type='text' class="input" id='descriptionInput' placeholder='Description'></textarea>
<input ng-model="venueCtrl.venue.tags" type='text' class="input" id='tagsInput' placeholder='Who did you go with?'/>
<label>Have you already been?</label>
<input ng-model="venueCtrl.venue.check" type="checkbox" checked />
<div> venueForm is {{venueForm.$valid}} </div>
<input type="submit" value="Add Venue"/>
</form>
</section>
app.js
(function() {
var app = angular.module('repertoire', ['repertoire-venues']);
//var app = new Firebase('https://xyz.firebaseio.com/');
app.controller("VenueController", ['$http', function($http){
var venue = this;
venue.info = [ ];
$http.get('venues.json').success(function(data){
venue.info = data;
});
}]);
})();
repertoire-venues.js
(function() {
var app = angular.module('repertoire-venues', []);
app.directive('venueList', function(){
return {
restrict: 'E',
templateUrl: 'venue-list.html'
};
});
app.directive('venueForm', function(){
return {
restrict: 'E',
templateUrl: 'venue-form.html'
controller: function(){
this.venue = {};
this.venueForm = function(info){
info.venues.push(this.venue);
this.venue = {};
};
},
controllerAs: 'venueCtrl'
};
});
})();
Thank you so much <3
you have included venues.js instead of repertoire-venues.js in the index page and there is a comma missing on line 14 in repertoire-venues.js

Angular controller not working

I'm newbie to angular
My angular controller is:
var chatApp = angular.module('chatApp.controllers', []);
chatApp.controller('loginController', ['$scope', function($scope) {
$scope.user_name="name";
$scope.user_password="name";
}]);
the app.js is:
'use strict';
angular.module('chatApp', [
'ui.router',
'chatApp.filters',
'chatApp.services',
'chatApp.directives',
'chatApp.controllers'
]).config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('login', {
url: "/login",
templateUrl: "partials/login.html",
controller : "loginController"
})
});
login.html is:
<div>
<div id="wrapper">
<form name="login-form" class="login-form" action="" method="post">
<div class="header">
<h1>Login Form</h1>
</div>
<div class="content">
<input name="username" type="text" class="input username" placeholder="{{user_name}}" />
<div class="user-icon"></div>
<input name="password" type="password" class="input password" placeholder="{{user_password}}" />
<div class="pass-icon"></div>
</div>
</form>
</div>
I've used stateprovider for routing.
But, it's not showing anything in placeholder. What is the reason?
Solved the problem using ng-model instead of {{}}.
<div class="content">
<input name="username" type="text" class="input username" placeholder="username" ng-model="user_name" />
<div class="user-icon"></div>
<input name="password" type="password" class="input password" placeholder="password" ng-model="user_password"/>
<div class="pass-icon"></div>
</div>
This works for me if I say ng-controller = "loginController" in the html-
<div ng-controller = 'loginController'>
<div id="wrapper">
<form name="login-form" class="login-form" action="" method="post">
<div class="header">
<h1>Login Form</h1>
</div>
<div class="content">
<input name="username" type="text" class="input username" placeholder="{{user_name}}" />
<div class="user-icon"></div>
<input name="password" type="password" class="input password" placeholder="{{user_password}}" />
<div class="pass-icon"></div>
</div>
</div>
Here's a JSBin with it working: http://jsbin.com/aDuJIku/265/edit?html,js,output
This solution doesn't include ui-router, but it should work with it.
Try this:
var chatApp = angular.module('chatApp.controllers', []);
chatApp.controller('loginController', ['$scope','$timeout', function($scope,$timeout) {
$timeout(function(){
$scope.user_name="name";
$scope.user_password="name";
},100);
}]);
you just have to change to RouteProvider, In your case you just do:
angular.module('chatApp', [ 'ngRoute' 'ui.router','chatApp.filters','chatApp.services', 'chatApp.directives', 'chatApp.controllers'])
.config(function($routeProvider) {
$routeProvider.when('/login', { templateUrl: "partials/login.html", controller: "loginController" })
});
please make sure that you have angular-route js included.
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.11/angular.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.11/angular-route.js"></script>
Hope this help you! ;)
Here's some examples for you this
Below mentioned code works.
Note: If somebody tries to run this code in preview its not going to work. JS and HTML code needs to be copied in separate file and use the names mentioned.
var myContrlApp = angular.module('ContrlApp', []);
myContrlApp.controller('MainController', function ($scope) {
var person = {
firstName: "Keith",
lastName: "Jackson",
};
$scope.message = "Welcome, Angular !";
$scope.person = person;
});
<html ng-app="ContrlApp">
<head>
<script type="text/javascript" src="Scripts/angular.js"></script>
<script type="text/javascript" src="Scripts/angular-route.js"></script>
<script type="text/javascript" src="Scripts/script.js"></script>
<!--<link rel="stylesheet" href="style.css" />-->
<title>Angular JS Tryout</title>
</head>
<body ng-controller="MainController">
<div>
<h1>{{message}}</h1>
<div>
<div>First name: {{person.firstName}}</div>
<div>Last name: {{person.lastName}}</div>
</div>
</div>
</body>
</html>

AngularJS data binding Form properties in template

I have a simple AngularJS app with a single form that has 2 fields on it. I am trying to read the values entered in those 2 fields from my controller but for some reason I am always getting undefined. I have triple checked my code but can't find anything in it, so I hope someone can please help and tell me what I am doing wrong and how to fix it.
Note: I am using latest AngularJS release 1.2
app.js
'use strict';
var myApp = angular.module('myApp', ['ngRoute','ngSanitize']);
myApp.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/index',
{ templateUrl: 'templates/common/index.html',
controller: 'IndexController'
}).
when('/editcontact',
{ templateUrl: 'templates/contacts/editContact.html',
controller: 'editContactController'
}).
otherwise({redirectTo: '/index'});
}]);
index.html
<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
<meta charset="utf-8">
<title>myApp</title>
....
....
<script src="lib/angular/angular.js"></script>
<script src="lib/angular/angular-route.js"></script>
<script src="lib/angular/angular-sanitize.js"></script>
<script src="js/app.js"></script>
<script src="js/controllers/contacts/editContactController.js"></script>
</body>
</html>
editContact.html
<form name="editContactForm">
<div>
<fieldset>
<input id="name" type="text" placeholder=Name..." ng-modal="contacts.name">
<input id="phone" type="text" placeholder="Phone" ng-modal="contacts.phone">
</fieldset>
<button type="submit" ng-click="saveContact(contacts, editContactForm)">Save</button>
<button type="button" ng-click="cancelEdit()">Cancel</button>
</div>
</form>
editContactController
myApp.controller('editContactController',
function editContactController($scope){
$scope.saveContact = function(contacts, editContactForm){
if(editContactForm.$valid){
console.log(contacts.name);
}
};
});
You have a typo. ng-modal should be ng-model
<input id="name" type="text" placeholder=Name..." ng-modal="contacts.name">
<input id="phone" type="text" placeholder="Phone" ng-modal="contacts.phone">
should be
<input id="name" type="text" placeholder=Name..." ng-model="contacts.name">
<input id="phone" type="text" placeholder="Phone" ng-model="contacts.phone">

Categories

Resources