Forgive me for my novelty with Angular but I can't find what the problem to this seemingly simple program. Instead of the $scope displaying "Jonathan" which is defined LoginController, it displays {{logins.username}} in login.html. If I move the controller in the index.html, it works fine. When I move it to app.js file, it does not work. Any help or direction would be greatly appreciated. Focusing on LoginController, below is my code:
Index.html
<!DOCTYPE html>
<html ng-app="millersFormalsApp">
<head>
<meta charset="UTF-8" />
<!-- This add the Angular JS to the program -->
<script src="js/angular.min.js"></script>
<script src="js/angular-route.min.js"></script>
<script src="js/app.js"></script>
<!-- load the logo -->
<img src="img/millers_icon.png">
</head>
<body>
<h2> AngularJS Project</h2>
<div class="container">
<div id="menu">
Home
Login
Register
</div>
<div ng-view=""></div>
</div>
</body>
</html>
login.html
<h2> Login Page</h2>
Username:
<input type="text" placeholder="Username" ng-model="logins.username"
<br />
Password:
<input type="text" placeholder="Password" ng-model="logins.password"
<h2>Your Username is {{ logins.username }} </h2>
app.js
var millersFormalsApp = angular.module('millersFormalsApp', ['ngRoute']);
//** Route Provider takes care of routing functionality based
//** upon what has been selected
millersFormalsApp.config(function ($routeProvider){
$routeProvider
.when('/',
{
controller: 'HomeController',
templateUrl: 'Views/home.html'
})
.when('/login',
{
controller: 'LoginController',
templateUrl: 'Views/login.html'
})
.when('/register',
{
controller: 'RegisterController',
templateUrl: 'Views/register.html'
})
.otherwise({redirectTo: 'home.html'});
});
//** Controllers are called by the Route Provider to specifically execute
//** the selected item
millersFormalsApp.controller('HomeController', function ($scope)
{
$scope.homePage = "This is Miller's Home Page";
});
millersFormalsApp.controller('LoginController', function ($scope)
{
$scope.logins = {username: "Jonathan", password: ""};
console.log($scope);
});
millersFormalsApp.controller('RegisterController', function ($scope) {
$scope.register = { firstname: "", lastname: "" };
console.log($scope);
});
Related
i am trying to code this and just Jump form 1 page to another page using routes but doesn't why its not working i search and tricks a lot but still failed please any one?
index.html
<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
<title>Angular Js</title>
<script type="text/javascript" src="angular.min.js"></script>
<script src="controller.js"></script>
<script src="angular-route.min.js"></script>
</head>
<body>
<div ng-view></div>
</body>
</html>
----------
Controler.js
var myRoute=angular.module('myApp',['ngRoute']);
myRoute.config(function($routeProvider){
$routeProvider
.when('/',{
template:'Welcome to Home'
})
.when('/NewPage',{
template:'This Is New Page Task'
})
otherwise('/',{
redirectTo:'/'
});
});
The order of references should be,
<script type="text/javascript" src="angular.min.js"></script>
<script src="angular-route.min.js"></script>
<script src="controller.js"></script>
app.config(function ($routeProvider) {
$routeProvider
.when("/", {
templateUrl: "route/one"
})
.when("/one", {
templateUrl: "route/one"
});
});
templateUrl is the place where you define your view is...In here my view(one.cshtml) is in route folder. Try the following example. Its working example.
<body ng-app="sampleApp">
<div class="container">
<div class="row">
<div class="col-md-3">
<ul class="nav">
<li> Add New Order </li>
<li> Show Order </li>
</ul>
</div>
<div class="col-md-9">
<div ng-view></div>
</div>
</div>
</div>
</body>
<script>
sampleApp.config(['$routeProvider',
function ($routeProvider) {
$routeProvider
.when('/AddNewOrder', {
templateUrl: '/viewStudents.html',
controller: 'AddOrderController'
})
.when('/ShowOrders', {
templateUrl: '/Home.html',
controller: 'ShowOrdersController'
})
.otherwise({ redirectTo: '/viewStudents' });
}]);
sampleApp.controller('AddOrderController', function ($scope) {
$scope.message = 'This is Add new order screen';
});
sampleApp.controller('ShowOrdersController', function ($scope) {
$scope.message = 'This is Show orders screen';
});
</script>
I wrote the program that is having 3 buttons and if i click on the particular button it should redirect to corresponding page mentioned in app.js
my requirement is each button should have a controller and it should redirect properly and it should show a console message that which button is clicked
i'm sharing my code but it is not working
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Test</title>
<link data-require="bootstrap-css" data-semver="3.1.1" rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" />
<!-- Le javascript
================================================== -->
<script data-require="jquery" data-semver="2.0.3" src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
<script data-require="bootstrap" data-semver="3.1.1" src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular-route.min.js"></script>
<script>var myItemsApp = angular.module('myItemsApp', ['ngRoute']);</script>
</head>
<body ng-app="myItemsApp">
<div>
<h3>Test</h3>
<div class="row">
<div class="col-md-4">
<button href="/test1" ng-click="submit1()">Button1</button>
<button href="/test2" ng-click="submit2()">Button2</button>
<button href="/test3" ng-click="submit3()">Button3</button>
</div>
</div>
</div>
</div>
<script src="app.js"></script>
</body>
<script src="testcntrl.js"></script>
</html>
#app.js
myItemsApp.config(['$routeProvider',function($routeProvider) {
$routeProvider
.when('/test1', {
templateUrl : 'test.html',
controller : 'button1Controller'
})
.when('/test2', {
templateUrl : 'test1.html',
controller : 'button2Controller'
})
.when('/test3', {
templateUrl : 'test2.html',
controller : 'button3Controller'
})
.otherwise({
redirectTo: '/'
});
}]);
testcntrl.js
myItemsApp.controller('button1Controller', ['$scope','$location', function($scope,location){
$scope.submit1 = function() {
console.log("I clicked on submit button1Controller");
location.path('/test1');
}
}]);
myItemsApp.controller('button2Controller', ['$scope','$location', function($scope,location){
$scope.submit2 = function() {
console.log("I clicked on submit button2Controller ");
location.path('/test2');
}
}]);
myItemsApp.controller('button3Controller', ['$scope','$location', function($scope,location){
$scope.submit3 = function() {
console.log("I clicked on submit button3Controller");
location.path('/test3');
}
}]);
test1.html
<h1>hello</h1>
You should add ng-view to render template. and add # to url in the href.
also you don't need ng-click when time using <a> tag.and you injected service into controller incorrectly. you should inject $location instead of location
if you want to remove # from url so enable html mode.
<div class="col-md-4">
<a href="#/test1" >Button1</a>
<a href="#/test2" >Button2</a>
<a href="#/test3" >Button3</a>
</div>
<div ng-view=""></div>
</div>
Demo
Your idea is ok, it should work but:
No need href in button.
Instead of button you can simply use anchor with #/test1 #/test2
If you still want this way you need another controller "main controller"
This can work:
// Code goes here
var myItemsApp = angular.module('myItemsApp', ['ngRoute']);
myItemsApp.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/test1', {
templateUrl: 'test1.html',
controller: 'button1Controller'
})
.when('/test2', {
templateUrl: 'test2.html',
controller: 'button2Controller'
})
.when('/test3', {
templateUrl: 'test3.html',
controller: 'button3Controller'
})
.otherwise({
redirectTo: '/'
});
}]);
myItemsApp.controller('initialController', ['$scope', '$location', function($scope, location) {
$scope.submit1 = function() {
console.log("I clicked on submit button1Controller");
location.path('/test1');
}
$scope.submit2 = function() {
console.log("I clicked on submit button2Controller ");
location.path('/test2');
}
$scope.submit3 = function() {
console.log("I clicked on submit button3Controller");
location.path('/test3');
}
}]);
myItemsApp.controller('button1Controller', ['$scope', '$location', function($scope, location) {
}]);
myItemsApp.controller('button2Controller', ['$scope', '$location', function($scope, location) {
}]);
myItemsApp.controller('button3Controller', ['$scope', '$location', function($scope, location) {
}]);
Plunker demo
I am using this code to view and add peoples in an array.
index.html
<!DOCTYPE html>
<html ng-app="myApp">
<body>
<h1>People</h1>
<div ng-controller="Ctrl">
<div ng-view></div>
</div>
<script src="angular.min.js"></script>
<script src="angular-route.min.js"></script>
<script src="controller.js"></script>
</body>
</html>
add.html
<h1>Add</h1>
<input type="text" ng-model="new_name" placeholder="Name">
<br />
<input type="text" ng-model="new_age" placeholder="Age">
<br />
<button ng-click="add()">Add</button>
<hr />
Back
controller.js
var app = angular.module('myApp', ['ngRoute']);
app.config(function ($routeProvider){
$routeProvider
.when('/',{
templateUrl: 'list.html'
})
.when('/add',{
templateUrl: 'add.html',
});
});
app.controller('Ctrl', function($scope) {
$scope.people = [{'name':'Alex', 'age':25}, {'name':'Dan', 'age': 25}];
$scope.add = function(){
$scope.people.push({'name':$scope.new_name, 'age':$scope.new_age});
$location.path("/");
};
});
The problem is, I am not getting data from ng-model="new_name" into the controller method $scope.add = function(). After pressing add button only blank strings gets pushed into array. However the model and controller working perfectly without routing and ng-view directive. I think its scope related problem. Can any body help me in this.
Thanks.
Because you should specify the controller for each view. So try doing this:
app.config(function ($routeProvider){
$routeProvider
.when('/',{
templateUrl: 'list.html',
controller: 'Ctrl'
})
.when('/add',{
templateUrl: 'add.html',
controller: 'Ctrl'
});
});
A better solution would be to have a separate controller for each view. Also, have a look at the $routeProvider documentation.
Just delete <div ng-controller="Ctrl"> from index.html and add a controller attribute for your route.
controller.js
var app = angular.module('myApp', ['ngRoute']);
app.config(function ($routeProvider){
$routeProvider
.when('/',{
templateUrl: 'list.html'
})
.when('/add',{
templateUrl: 'add.html',
controller: 'Ctrl'
});
});
app.controller('Ctrl', function($location,$scope) {
$scope.people = [{'name':'Alex', 'age':25}, {'name':'Dan', 'age': 25}];
$scope.add = function(){
$scope.people.push({'name':$scope.new_name, 'age':$scope.new_age});
$location.path("/");
};
});
index.html
<!DOCTYPE html>
<html ng-app="myApp">
<body>
<h1>People</h1>
<div ng-view></div>
<script src="angular.min.js"></script>
<script src="angular-route.min.js"></script>
<script src="controller.js"></script>
</body>
</html>
first you have to wrap your inputs with <form> tag with name='' attribute.
Next step is to give name='' attributes for each <input> tag. Look:
<form name='myLoginForm'>
<input name='nick' ng-model='loginFormModel.nick'>
<input name='password' ng-model='loginFormModel.password'>
</form>
In controller:
app.controller('Ctrl', function($location,$scope) {
$scope.loginFormModel = {}; //now you have whole values from view in this variable, for example nick is available in $scope.loginFormModel.nick
});
basically my issue is that I have a AngularJS view (home.html) which contains a variable in double brackets like so: {{message}}
When the $scope.message variable is modified, the view with does not update, although it should? I have tried adding $scope.$apply() which results in an exception along the lines of 'Action in Progress'
Check my code below. The {{message}} part in home.html is not being updated when $scope.doLogin is called in MainCtrl, even though I have set $scope.message to a new value in that function.
Any help is greatly appreciated and if any further info is needed, please ask.
index.html
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet">
<link href="stylesheet.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.4/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.4/angular-route.min.js"></script>
<base href="/">
<script src="https://cdnjs.cloudflare.com/ajax/libs/ngStorage/0.3.9/ngStorage.js"></script>
<script src="https://cdn.socket.io/socket.io-1.3.5.js"></script>
</head>
<body>
<div ng-controller="MainCtrl">
<nav class="navbar navbar-default">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="#">TriviaAttack</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<form id="loginForm" class="navbar-form navbar-right">
<div class="form-group">
<input type="text" placeholder="Email" class="form-control" ng-model="loginData.username">
</div>
<div class="form-group">
<input type="text" placeholder="Password" class="form-control" ng-model="loginData.password">
</div>
<div class="form-group">
<button type="submit" class="btn btn-success" ng-click="doLogin()">Sign In</button>
</div>
</form>
</div>
</div>
</nav>
</div>
<div ng-view>
</div>
</div>
<script src="./app/app.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js">
</body>
</html>
home.html
<div>
<h1>Welcome to the Home Page</h1>
<p>{{message}}</p>
</div>
app.js
var myApp = angular.module('myApp',['ngRoute', 'ngStorage']);
myApp.controller('MainCtrl', ['$rootScope', '$scope', '$location',
function($rootScope, $scope, $location) {
$scope.message = 'testing message';
$scope.loginData = {
username: '',
password: '',
loggedIn: false
}
$scope.doLogin = function() {
$scope.message = 'message changed!';
$scope.$apply();
Auth.doLogin($scope.loginData.username, $scope.loginData.password)
.success(function(data) {
if (data.success) {
AuthToken.setToken(data.token);
$location.path('/home');
console.log($scope.loginData.loggedIn);
}
});
$scope.loginData = {};
}
}]);
//Middleware for all requests which adds the users token to the HTTP header.
myApp.factory('TokenInterceptor', ['$q', '$location', '$localStorage',
function($q, $location, $localStorage) {
//On each request, check if the user is logged in with a valid token.
var interceptor = {
request: function(config) {
config.headers['X-Authorization-Token'] = $localStorage.token;
return config;
},
responseError: function(response) {
if(response.status === 401 || response.status === 403) {
$location.path('/login');
}
return $q.reject(response);
}
};
return interceptor;
}]);
myApp.config(['$routeProvider','$locationProvider','$httpProvider',
function($routeProvider, $locationProvider, $httpProvider) {
$routeProvider.
when('/', {
templateUrl: './app/views/landingpage.html',
controller: 'MainCtrl'
}).
when('/home', {
templateUrl: './app/views/home.html',
controller: 'MainCtrl'
}).
otherwise({
redirectTo: '/'
});
$locationProvider.html5Mode(true);
$httpProvider.interceptors.push('TokenInterceptor');
}
]);
console.log('app.js loaded!');
Each time a view is loaded ,the controller code with new scope executes so the new message is not reflected.
So the flow be like
landingPage's controller which is MainCtrl with its scope when $scope.doLogin is executed will change the $scope.message variable to "Message Changed" and upon changing location to home , the MainCtrl is assigned to home page with new scope which would continue executing the very first line of MainCtrl i.e.
$scope.message = 'testing message';
As you have decided to use common controller for login and home pages
Try removing controller option in
when('/', {
templateUrl: './app/views/landingpage.html',
controller: 'MainCtrl'
}).
when('/home', {
templateUrl: './app/views/home.html',
controller: 'MainCtrl'
})
And assign controller in
<div ng-controller="MainCtrl">
<!--omitted-->
<div ng-view></div>
</div>
Or else other options would be to pass parameters or use
ui-router wherein nested views would automatically inherit from parent controllers without rerunning the controller logic.
Problem is in controller coverage
<div ng-controller="MainCtrl">
<!--omitted-->
</div>
<div ng-view></div>
Your $scope.message is tight to your MainCtrl, so when ng-view is populated, you except that it has MainCtrl, but indeed it's outside of that div, so just doesn't see that variable, to make it work, insert ng-view to MainCtrl div like shown below
<div ng-controller="MainCtrl">
<!--omitted-->
<div ng-view></div>
</div>
But here's the actual problem
You tend to use ng-route but you don't have any route configurations, ng-view will never be populated with home.html unless you configure you routeProvider, first of all, make some routes like described here, perform your form action, redirect to page and populate views accordingly, it should work.
I am learning Angularjs from Tuts+ Easier JavaScript Apps with AngularJS tutorial. Now I am at the part where they discussed Routing Primer using ng-view. I am trying to show the list page contents in ng-view of index page. For some reason nothing is shown when I load index.html. I found from searching that From angular 1.2.0, ngRoute has been moved to its own module. I have to load it separately and declare the dependency. But still I can't show anything from my list page.
index.html
<!doctype html>
<html ng-app="myApp">
<head>
<title>Angular App</title>
<script src="js/angular.min.js"></script>
<script src="js/angular-route.min.js"></script>
<script src="app.js"></script>
</head>
<body>
<div ng-controller="Ctrl">
<div ng-view></div>
</div>
</body>
</html>
list.html
<h3>List</h3>
<ul>
<li ng-repeat="contact in contacts">
{{contact.name}}: {{contact.number}}
</li>
</ul>
app.js
var app = angular.module('myApp', ['ngRoute']);
app.config(function($routeProvider) {
$routeProvider.when('/', {
templateUrl: 'list.html',
controller: 'Ctrl'
});
});
app.controller('Ctrl', function($scope){
$scope.contacts = [
{ name: 'Shuvro', number: '1234' },
{ name: 'Ashif', number: '4321' },
{ name: 'Anik', number: '2314' }
];
});
Remove the ng-controller from the div like this:
<body>
<div >
<div ng-view></div>
</div>
</body>
To void "miss-routings" add the otherwise to the main configuration like: otherwise({ redirectTo: '/'});
app.config(function($routeProvider) {
$routeProvider.when('/', {
templateUrl: 'list.html',
controller: 'Ctrl'
}).otherwise({ redirectTo: '/'});
});
Online Demo