I'm learning Angular through a YouTube tutorial series. In the tutorial, you create username and password inputs, and then you use a controller and ngRoute to bring up a dashboard.html page when successful credentials are used. The problem is that when clicking the button, nothing happens, whether the proper credentials are entered or not. Everything is working on the tutorial, and I have triple checked the code thoroughly, and mine looks just like the code in the tutorial. I'm sure I must be missing something though.
What I think:
There is an issue with the click event firing, so maybe there is an issue with how I am calling the function?
The tutorial uses an older angular version (1.3.14), and maybe things have changed? I'm using 1.4.9, but I looked up the api data for the ng-click directive, and all seems well. I also tried using the older version to no avail.
I'm doing something wrong with ngRoute, potentially $scope misuse?
I am inserting all of the code below. Thanks for taking a look!
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Place Title Here</title>
<meta charset = "utf-8"/>
<meta http-equiv="X-UA-compatible" content="IE-edge, chrome=1">
<meta name = "viewport" content = "width = device - width, initial-scale = 1.0"/>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
<script src="angular-route.min.js"></script>
<script src="controller.js"></script>
</head>
<body ng-app="mainApp">
<div ng-view></div>
</body>
</html>
login.html
<div ng-controller="loginCtrl"></div>
<form action="/" id="myLogin">
Username: <input type="text" id="username" ng-model="username"><br>
Password: <input type="password" id="password" ng-model="password"><br>
<button type="button" ng-click="submit()">Login</button>
</form>
controller.js
var app = angular.module('mainApp', ['ngRoute']);
app.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'login.html'
})
.when('/dashboard', {
templateUrl: 'dashboard.html'
})
.otherwise({
redirectTo: '/'
});
});
app.controller('loginCtrl', function($scope, $location) {
$scope.submit = function() {
var uname = $scope.username;
var password = $scope.password;
if($scope.username == 'admin' && $scope.password == 'admin') {
$location.path('/dashboard');
}
else {
alert('Nope')
}
};
});
dashboard.html
Welcome User.
Your form needs to be inside the div with ng-controller
<div ng-controller="loginCtrl">
<form action="/" id="myLogin">
Username: <input type="text" id="username" ng-model="username"><br>
Password: <input type="password" id="password" ng-model="password"><br>
<button type="button" ng-click="submit()">Login</button>
</form>
</div>
Otherwise it won't have access to the submit() function.
Related
I'm new at AngularJS, started 2 days ago, but I can't resolve this problem.
The JS Console Error here
It seems that my directive ng-controller can't find my controller.
Here is my code :
<section class="index" ng-app="indexApp" ng-controller="cRegister">
<form>
<input type="text" ng-model="username" />
<input type="password" ng-model="password" />
<input type="submit" ng-click="" />
</form>
<script>
var app = angular.module('indexApp', [])
app.controller('cRegister', ['$scope', function() {
console.log('controller: true');
}]);
</script>
</section>
(This is a part of the main page, that I displayed with ng-view) :
<html ng-app="web">
<head>
<title>AngularJS, tries</title>
<meta charset="utf-8">
</head>
<body>
<div ng-view></div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular.min.js"></script>
<script src="https://code.angularjs.org/1.6.2/angular-route.min.js"></script>
<script>
var app = angular.module('web', ['ngRoute']);
app.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'partials/index.php'
})
.otherwise({
redirectTo: '/'
})
});
</script>
</body>
</html>
Hope someone could help me, thank you ! :D
you cannot have two ng-app directive in one html.
remove the inner one and add that controller to the first ng-app
I am having some problems running my first AngularJS app. When I run my app all objects on my index are displayed properly. When I click on my hyperlink to move to view-2 all objects are displayed on HTML like plain text {{object.property}} What am I doing wrong?
This is my index.html:
<DOCTYPE html>
<html ng-app="tutorialApp">
<head>
<meta charset="UTF-8">
<title> Tutorial App</title>
<script src="lib/angular.min.js"></script>
<script src="lib/angular-route.min.js"></script>
<script src="js/app.js"></script>
<script src="js/controllers/MyController.js"></script>
</head>
<body>
<div ng-view></div>
</body>
</html>
</DOCTYPE>
this is my app.js:
var app = angular.module('tutorialApp', ["ngRoute", "MyControllerModule"])
app.config(function ($routeProvider){
$routeProvider
.when("/", {
controller: "MyController",
templateUrl: "views/one.html"
})
.when("/two", {
controller: "ControllerTwo",
templateUrl: "views/two.html"
})
.otherwise({
redirectTo: "/"
});
});
this is my MyController.js:
angular.module("MyControllerModule", [])
.controller("MyController", ["$scope", function($scope){
$scope.myFirstObject = {};
$scope.myFirstObject.title = "Main Page";
$scope.myFirstObject.subTitle = "Sub Title";
$scope.myFirstObject.bindOutput = 13;
$scope.myFirstObject.firstname = "Wheelchair";
$scope.myFirstObject.lastname = "Terminator";
$scope.timesTwo = function(){
$scope.myFirstObject.bindOutput *= 2;
}
}])
.directive("myFirstDirective", function(){
return {
restrict: "E",
template: "<div>Hello how are you?</div>"
}
})
.controller("ControllerTwo", ["$scope", function($scope) {
$scope.testObject = {};
$scope.testObject.doSomething = "TEST TEST TEST TEST TEST!";
}
]);
This is my /views/one.html:
<h1>{{myFirstObject.title}}</h1>
<h2>{{myFirstObject.subTitle}}</h2>
<p>Number: {{2 + 2}}</p>
<p>String: {{myFirstObject.firstname + " " + myFirstObject.lastname}}</p>
<p><b>Multiply a number by two: {{myFirstObject.bindOutput | currency}}</b></p>
<button ng-click="timesTwo()">CLICK TO MULTIPLY</button><br>
<br>
<label>First Name:</label>
<input ng-model="myFirstObject.firstname">
<br>
<label>Last Name:</label>
<input ng-model="myFirstObject.lastname">
<br>
CLICK HERE FOR SECOND VIEW
<br>
<br>
<br>
<my-first-directive></my-first-directive>
this is my /views/two.html
<h1>Second View</h1>
<h2>this is the second view...</h2>
<br>
<br>
<p>Call object string: {{testObject.doSomething}}</p>
Change the href to route. Not html page.
CLICK HERE FOR SECOND VIEW
This should be
CLICK HERE FOR SECOND VIEW
As you did in the question, that calls the new html page to load into the browser. Not template of angular app. So, all the unknown stuff like {{object.property}} happens.
Use,
CLICK HERE FOR SECOND VIEW
Observe, href="#two"
<h1>{{myFirstObject.title}}</h1>
<h2>{{myFirstObject.subTitle}}</h2>
<p>Number: {{2 + 2}}</p>
<p>String: {{myFirstObject.firstname + " " + myFirstObject.lastname}}</p>
<p><b>Multiply a number by two: {{myFirstObject.bindOutput | currency}}</b></p>
<button ng-click="timesTwo()">CLICK TO MULTIPLY</button><br>
<br>
<label>First Name:</label>
<input ng-model="myFirstObject.firstname">
<br>
<label>Last Name:</label>
<input ng-model="myFirstObject.lastname">
<br>
CLICK HERE FOR SECOND VIEW
<br>
<br>
<br>
<my-first-directive></my-first-directive>
Check this reference
EDIT:
You seems to have issue with # url's
Solution:
HTML5 Mode
Configuration:
$routeProvider
.when('/two', {
templateUrl: 'views/two.html',
});
$locationProvider
.html5Mode(true);
You should set the base in HTML-file
<html>
<head>
<base href="/">
</head>
</html>
In this mode you can use links without the # in HTML files
link
example:
http://test.com/base/two
My question is about handling client side validations for a large Angular app. I have a big SPA app with different components which includes reusable components like zip control. Now I can integrate these components in my page form but how can I trigger the validations for elements residing within the components. For e.g. my zip component has city input box, state select box and zip input box, now how can I trigger validations for these components from form submit?
I am using the following solution for my application for now. I am able to validate the required fields with this solution.
I created two input field one from the directive and other within the form. I am able to show error messages for both the fields. Similarly this can be done for some other form of validations.
Here is my plunker
https://plnkr.co/edit/laW9jYoNCszHlPeIl3Vs?p=preview
script.js
var app = angular.module('validationModule', []);
app.controller('mainCtrl', mainCtrl);
app.directive('testDirective', testDirective);
function testDirective(){
var testDirective = {
template: 'First Name: <input type="text" name="fName" required ng-model="user.firstName">'
};
return testDirective;
}
mainCtrl.$inject = ['$scope'];
function mainCtrl($scope){
$scope.submitForm = function(user){
alert(user.firstName + " " + user.lastName);
}
}
Index.html file
<!DOCTYPE html>
<html ng-app="validationModule">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.9/angular.js" charset="UTF-8"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.9/angular-animate.js" charset="UTF-8"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.9/angular-sanitize.js" charset="UTF-8"></script>
<script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-2.3.1.js" charset="UTF-8"></script>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<script src="script.js"></script>
</head>
<body ng-controller="mainCtrl">
<form name="myForm" ng-submit="myForm.$valid? submitForm(user) : ''" novalidate>
<h1>Input User Name</h1><br/>
<test-directive></test-directive><br/>
Last Name: <input type="text" name="lName" required ng-model="user.lastName">
<button type="submit" class="btn btn-danger">Submit</button>
<div class="alert alert-danger" ng-show="myForm.$submitted">
<div ng-show="myForm.fName.$error.required">
First Name is required
</div>
<div ng-show="myForm.lName.$error.required">
Last Name is required
</div>
</div>
<br/><br/><br/>
<h1>Is form valid? {{myForm.$valid}}</h1>
</form>
</body>
</html>
AngularJS is new to me (and difficult). So I would like to learn how to debug.
Currently I'm following a course and messed something up. Would like to know how to interpret the console error and solve the bug.
plnkr.co code
index.html
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.min.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-controller="MainController">
<h1>{{message}}</h1>
{{ username }}
<form action="searchUser" ng-submit="search(username)">
<input type="search"
required placeholder="Username to find"
ng-model="username"/>
<input type="submit" value="search">
</form>
<div>
<p>Username found: {{user.name + error}}</p>
<img ng-src="http://www.gravatar.com/avatar/{{user.gravatar_id}}" title="{{user.name}}"/>
</div>
</body>
</html>
script.js
(function() {
var app = angular.module("githubViewer", []);
var MainController = function($scope, $http) {
var onUserComplete = function(response) {
$scope.user = response.data;
};
var onError = function(reason) {
$scope.error = "could not fetch data";
};
$scope.search = function(username) {
$http.get("https://api.github.com/users/" + username)
.then(onUserComplete, onError);
};
$scope.username = "angular";
$scope.message = "GitHub Viewer"; };
app.controller("MainController", MainController);
}());
The console only says
searchUser:1 GET http://run.plnkr.co/lZX5It1qGRq2JGHL/searchUser? 404
(Not Found)
Any help would be appreciated.
In your form, action you have written this
<form action="searchUser"
What this does is it will try to submit to a url with currentHostName\searchUser, so in this case your are testing on plunker hence the plunker url.
You can change the url where the form is submitted. Incase you want to search ajax wise then you dont even need to specify the action part. You can let your service/factory make that call for you.
Though not exactly related to debugging this particular error, there is a chrome extension "ng-inspector" which is very useful for angularJS newbies. You can view the value each of your angular variable scopewise and their value. Hope it helps!
Here is the link of the chrome extension: https://chrome.google.com/webstore/detail/ng-inspector-for-angularj/aadgmnobpdmgmigaicncghmmoeflnamj?hl=en
Since you are using ng-submit page is being redirected before the response arrives and you provided any action URL as searchUser which is not a state or any html file so it being used to unknown address, it is async call so it will take some time you can use input types as button instead of submit.
Here is the working plunker.
<!DOCTYPE html>
<html ng-app="githubViewer">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.min.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-controller="MainController">
<h1>{{message}}</h1>
{{ username }}
<form >
<input type="search"
required placeholder="Username to find"
ng-model="username"/>
<input type="button" ng-click="search(username)" value="search">
</form>
<div>
<p>Username found: {{user.name + error}} {{user}}</p>
<img ng-src="http://www.gravatar.com/avatar/{{user.gravatar_id}}" title="{{user.name}}"/>
</div>
</body>
</html>
I am a beginner with MEAN Stack development. I was trying out to play around with some angular stuff but got completely messed up the the controllers.
Here is my main html file
<!--main.html-->
<html>
<head>
<title>Chirp</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js"></script>
<script src="javascripts/chirpApp.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
<link rel="stylesheet" href="stylesheets/style.css">
</head>
<body ng-app="chirpApp">
<div id='main' class="container" ng-controller="mainController">
<div class="col-md-offset-2 col-md-8">
<div class="clearfix">
<form ng-Submit="post()">
<input required type="text" class="form-control" placeholder="Your name" ng-model="newPost.created_by" />
<textarea required class="form-control" maxlength="200" rows="3" placeholder="Say something" ng-model="newPost.text"></textarea>
<input class="btn submit-btn pull-right" type="submit" value="Chirp!" />
</form>
<div id="post-stream">
<h4>Chirp Feed</h4>
<div class="post" ng-repeat="post in posts | orderBy:'created_at':true" ng-class-odd="'odd'" ng-class-even="'even'">
<p>{{post.text}}</p>
<small>Posted by #{{post.created_by}}</small>
<small class="pull-right">{{post.created_at | date:"h:mma 'on' MMM d, y"}}</small>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
I have created another html file for registration. here is the code for it.
<!--register.html-->
<html>
<head>
<title>Chirp</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js"></script>
<script src="javascripts/chirpApp.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
<link rel="stylesheet" href="stylesheets/style.css">
</head>
<body ng-app="chirpApp">
<div id='main' class="container" ng-controller="authController">
<form class="form-auth" ng-submit="register()">
<h2>Register</h2>
<p class="text-warning">{{error_message}}</p>
<input type="username" ng-model="user.username" placeholder="Username" class="form-control"><br>
<input type="password" ng-model="user.password" placeholder="Password" class="form-control"><br>
<input type="submit" value="Register" class="btn btn-primary" />
</form>
</div>
</body>
</html>
I have created two separate controllers for registration and posts. the first controller works nicely but whenever I am trying to add a second controller I am getting an error message. Here is the code for my controllers.
//chirpApp.js
var app = angular.module('chirpApp', []);
app.controller('mainController', function($scope){
$scope.posts = [];
$scope.newPost = {created_by: '', text: '', created_at: ''};
$scope.post = function(){
$scope.newPost.created_at = Date.now();
$scope.posts.push($scope.newPost);
$scope.newPost = {created_by: '', text: '', created_at: ''};
};
});
app.controller('authController', function($scope){
$scope.user = {username: '', password: ''};
$scope.error_message = '';
$scope.login = function(){
//placeholder until authentication is implemented
$scope.error_message = 'login request for ' + $scope.user.username;
};
$scope.register = function(){
//placeholder until authentication is implemented
$scope.error_message = 'registeration request for ' + $scope.user.username;
};
});
I am getting the following error in the chrome console :
Error: [ng:areq] http://errors.angularjs.org/undefined/ng/areq?p0=authController&p1=not%20a%20function%2C%20got%20undefined
at Error (native)
at https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js:6:453
at tb (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js:18:250)
at Oa (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js:18:337)
at $get (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js:61:288)
at https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js:48:476
at q (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js:7:367)
at S (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js:48:342)
at h (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js:43:59)
at h (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js:43:76)
main.html works fine and the data is being binded successfully.
The issue is with the register.html page. I suppose the authController is not getting binded
Can anyone suggest me the best way of implementing the same? And why the controller is getting undefined?
Try the following checklist:
angularjs lib is included in
ng-app=".." directive is in index.html
..path/to/module and other controllers in index.html
module and controllers defined correctly (spelling, syntax etc)
Controller example (if not using global angular var:
app.controller('AppController', ['$http', '$scope', '$log',
function($http, $scope, $log) {
// TODO: implement
}
]);
Hope this helps.
Here is the plunker of your files
http://embed.plnkr.co/6jNXImBddYqjK23FCWUy/preview
Your application works as expected. Please check your core files is loaded or not.
Hope this helps
your code
When you create a new controller with the AngularJS Controller Sub-Generator you have to reboot Grunt.