I've ben struggling with this for days, I can't see where is wrong. Thing is I've set up a angularjs web with routing and controllers but the controllers are showing the data empty in the views, but in the console I can see the $scope output with the corect data throught a console.log($scope). Here is the code
index.html
<html>
<head>
<link rel="stylesheet" type="text/css" href="http://getbootstrap.com/dist/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="css/style.css">
<script src="bower_components/angular/angular.js"></script>
<script src="bower_components/angular-md5/angular-md5.js"></script>
<script src="bower_components/angular-route/angular-route.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js">
/script><sctipt src="http://getbootstrap.com/dist/js/bootstrap.min.js">
/sctipt><script src="js/main.js"></script>
</head>
<body ng-app='app'>
<div ng-view></div>
</body>
</html>
login.html
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="wrap">
<p class="form-title">
{{signin}}</p>
<form class="login">
<input type="text" ng-placeholder="{{user}}" required/>
<input type="password" ng-placeholder="{{password}}" required/>
<input type="submit" value="{{signin}}" class="btn btn-success btn-sm" />
<div class="remember-forgot">
<div class="row">
<div class="col-md-5">
<div class="checkbox">
<label>
<input type="checkbox" />
{{rememberme}}
</label>
</div>
</div>
<div class="col-md-7 forgot-pass-content">
{{forgotpassword}}}
</div>
</div>
</div>
</form>
</div>
</div>
</div>
main.js
var app=angular.module('app',['ngRoute']);
app.config(['$locationProvider','$routeProvider',function ($locationProvider,$routeProvider){
$routeProvider.
when('/login',{
templateUrl:'html/login.html',
controller:'loginController'
}).
when('/home',{
templateUrl:'html/home.html',
controller:'homeController'
}).
otherwise({
redirectTo:'/login'
});
}]);
app.run(function($rootScope){
$rootScope.urlapi='http://freecalendar.desirnet.com/api/api.php';
});
app.controller('loginController',function($scope,$rootScope,$location){
$scope={
'singin':'Iniciar sesión',
'user':'Usuario',
'password':'Contraseña',
'rememberme':'Recuérdame',
'forgotpassword':'Recordar contraseña'
};
console.log($scope);
$scope.login=function(){
var data=$.param({
'user':$scope.txtuser,
'password':$scope.txtpassword
});
$http.post($rootScope.urlapi,data)
.then(function(response){
response=response.data;
console.log(response);
if(response.error!=undefined){
$scope.errorlogin="El usuario y/o contraseña no son correctos";
} else {
$location.path('/home')
}
});
}
});
app.controller('homeController',function($scope,$rootScope,$location){
});
I really don't know what I'nm doing wrong, I follow many routing tutorials, but nothing.
In the console there are no errors only the $scope output.
typographical error in these line of code:
/sctipt>
You are assigning a new value to the $scope parameter in your loginController function
$scope={
'singin':'Iniciar sesión',
'user':'Usuario',
'password':'Contraseña',
'rememberme':'Recuérdame',
'forgotpassword':'Recordar contraseña'
};
You need to understand that after that you loose the link to the actual scope Angular is using. Angular simply has no way of knowing what are you intentions in your controller.
Here is the piece of code that will do the trick:
Object.assign($scope, {
'singin':'Iniciar sesión',
'user':'Usuario',
'password':'Contraseña',
'rememberme':'Recuérdame',
'forgotpassword':'Recordar contraseña'
});
Notice that it simply adds a few properties to the $scope object therefore Angular can perfectly reflect changes from your controller in your view.
Related
Getting Data from database with php. Data is fine. Butt data is not showing in NgModel box. I have passed scope parameter in ngdialog function. Please help me out.
var adminapp = angular.module("uibootstrap", ["ngRoute", 'ngDialog']);
adminapp.controller("homedata", function($scope, $rootScope, $http, $httpParamSerializerJQLike, ngDialog, $timeout) {
$rootScope.theme = 'ngdialog-theme-default';
$scope.openDefault = function() {
ngDialog.open({
template: 'firstDialogId',
className: 'ngdialog-theme-default',
scope: $scope
})
};
// get user
$http.get('http://localhost/database/get-user.php').success(function(response) {
$scope.users = response;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<li ng-repeat="item in users">
<a href="javascript:void(0);" ng-click="openDefault()">
<div class="img"><img alt="" src="admin/images/user-img2.jpg"> <span class="status-red"></span></div>
<div class="msginfo">
{{item.user_name}} <br> <span>{{item.user_status}}</span>
</div>
</a>
<script type="text/ng-template" id="firstDialogId">
<div class="ngdialog-message">
<div class="data">
<div class="img">
<img alt="" src="http://localhost/rockeditor/admin/images/img-user.png"> <a class="editbtn" href="#"><i class="fa fa-edit"></i></a>
</div>
<div class="name">{{item.user_name}}</div>
<span class="editor">{{item.user_status}}</span>
<span class="email">{{item.user_email}}</span>
<input class="btn-green" type="submit" value="Save">
</div>
</div>
</script>
</li>
variable item is not available in your template firstDialogId, actually it's not a child node of <li></li>
You forget to include controller in your html.
Use ng-controller="homedata" on <li> element
item is not accessible in that script tag
$scope.users is available after $http call returned with success response
See here
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="ngDialog.css" />
<link rel="stylesheet" href="ngDialog-theme-default.css" />
<script data-require="angular.js#*" data-semver="1.3.0" src="//code.angularjs.org/1.3.0/angular.js"></script>
<script src="ngDialog.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-app="MyApp" ng-controller="homedata">
<button ng-click="clickme()">Hello World</button>
<script type="text/ng-template" id="firstDialogId">
<div ng-repeat="user in users">
<div>Current user:</div>
<div>{{user.name}}</div>
</div>
</script>
</body>
</html>
script.js
// Code goes here
angular.module("MyApp", ['ngDialog'])
.controller("homedata", homedata)
function Main($scope, ngDialog) {
$scope.users = [
{name: 'abc'},
{name: 'xyz'}
];
$scope.clickme = function() {
ngDialog.open({
template: 'firstDialogId',
className: 'ngdialog-theme-default',
scope: $scope
});
};
}
But as per your controller, There is a $http call and until it responded you don't have any data in $scope.users. So, please make sure that it and you only get data in your dialog after the $http is get success response
I have the requirement, that all error messages have to be shown in the header of the application. How can I do that with angular?
If I have this application (see on plunker):
<body>
<div id="header">
<!-- I want error messages to show up here -->
</div>
<form name="myForm">
<label>Email</label>
<input name="myEmail" type="email" ng-model="user.email" required="" />
<div ng-messages="myForm.myEmail.$error">
<div ng-message="required">required</div>
<div ng-message="email">invalid email</div>
</div>
</form>
<p>Your email address is: {{user.email}}</p>
</body>
What I need is to have the error messages in the header div. How can I do that?
Fixed demo here.
Just access the error the way same as in form, as when you set <form name="myForm" >, then you will get $scope.myForm = [yourFormObject], then access free anywhere in same controller.
Angular Form Document
Under the title Binding to form and control state
A form is an instance of FormController. The form instance can optionally be published into the scope using the name attribute.
And, even access the $error in controller by $scope.$watch('formName.fieldName.$error',function(nv,ov){});
// Code goes here
var app = angular.module('plunker', ['ngMessages']);
app.controller('appCtrl', function($scope) {
$scope.$watch('myForm.myEmail.$error', function(nv, ov) {
console.info(nv);
}, true);
});
/* Styles go here */
hr {
margin: 20px 0;
}
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>
</script>
<link rel="stylesheet" href="style.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.5/angular.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.5/angular-messages.js"></script>
<script src="script.js"></script>
</head>
<body ng-controller="appCtrl">
<div id="header">
<div ng-show="myForm.myEmail.$error.required">required</div>
<div ng-show="myForm.myEmail.$error.email">invalid email</div>
</div>
<hr />
<form name="myForm">
<label>Email</label>
<input name="myEmail" type="email" ng-model="user.email" required="" />
<div ng-messages="myForm.myEmail.$error">
<div ng-message="required">required</div>
<div ng-message="email">invalid email</div>
</div>
</form>
<p>Your email address is: {{user.email}}</p>
</body>
</html>
You'll have two distinct controller.In header controller, you'll be displaying your error messages.
Then your controller will be communicating over either $rootScope or service
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.
I'm getting a curious error that seems to suggest my controller is not being created properly. Can anyone explain? This is my first SPA app so I'm programming in the dark a little bit.
Here is my master page:
<!DOCTYPE html>
<html ng-app="ibosApp">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>iBOS</title>
<script src="/Scripts/jquery-1.10.2.min.js"></script>
<script src="/Scripts/angular.min.js"></script>
<script src="/Scripts/angular-route.min.js"></script>
<script src="/Scripts/bootstrap-select.js"></script>
<script src="/angular/scripts/route-config.js"></script>
<script src="/Scripts/bootstrap-select.js"></script>
<link href="/Content/bootstrap.min.css" rel="stylesheet" />
<link href="/Content/bootstrap-select.css" rel="stylesheet" />
<link href="/Content/acs.css" rel="stylesheet"/>
<script type="text/javascript">
$(function () {
$('.selectpicker').selectpicker();
});
</script>
</head>
<body>
<div class="container body-content">
<ng-view/>
</div>
</body>
</html>
Here is my view template:
<div class="tab-content">
<div id="customers" class="tab-pane fade active in top-buffer" ng-controller="customerCtrl">
<form class="form-group">
<div class="container">
<div class="row">
<div class="col-sm-3">
<label for="customer-broker">Broker:</label>
<select class="selectpicker" id="customer-broker"></select>
</div>
<div class="col-sm-3">
<label for="customer-town">Town:</label>
<input type="text" class="form-control" id="customer-town"/>
</div>
<div class="col-sm-3">
<label for="customer-code">Code:</label>
<input type="text" class="form-control" id="customer-code"/>
</div>
<div class="col-sm-3">
<button ng-click="search()" class="btn">Search</button>
<button ng-click="myCustomers()" class="btn">My customers</button>
</div>
</div>
<div class="row">
<div class="col-sm-3">
<label for="customer-company-name">Company name:</label>
<input type="text" class="form-control" id="customer-company-name"/>
</div>
</div>
<div class="row">
<div class="col-sm-3">
<label for="customer-contact-name">Contact name:</label>
<input type="text" class="form-control" id="customer-contact-name"/>
</div>
</div>
<div class="row">
<div class="col-sm-3">
<label for="customer-customer-id">Customer ID:</label>
<input type="text" class="form-control" id="customer-customer-id"/>
</div>
</div>
</div>
</form>
</div>
</div>
<script type="text/javascript">
angular.module('ibosApp', ['angular-bootstrap-select', 'ngRoute'])
.controller("customerCtrl", function($scope, $http) {
$scope.loadBrokers = function() {
$http.get("/api/customers/getBrokers").success(function(data) {
$scope.brokers = data;
});
}
$scope.loadBrokers();
}
);
</script>
but I get the error "Argument 'customerCtrl' is not aNaNunction, got undefined" and the controller constructor is never called. Can anyone explain why?
M
EDIT - more code
Here is my route config...
angular.module("ibosApp", ["ngRoute"])
.config(function($routeProvider) {
$routeProvider.otherwise({
templateUrl: "/angular/components/booking-system/booking-system-template.html"
});
});
EDIT - full stack trace of error
Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.3.13/$injector/modulerr?p0=ibosApp&p1=Error%3…20d%20(http%3A%2F%2Flocalhost%3A4685%2FScripts%2Fangular.min.js%3A17%3A381)
There's a few things wrong.
You're setting ibosApp twice, i.e., angular.module("ibosApp", ["ngRoute"]) and angular.module("ibosApp", ['angular-bootstrap-select'])
You should only do this once, with all of your dependencies:
angular.module("ibosApp", ['ngRoute', 'angular-bootstrap-select']);
...and then use the getter syntax, which is the same, without the second parameter:
angular.module('ibosApp')
You can't define controllers in the view like you're doing unless you re-compile your angular app. It would be best to put your javascript into a separate file and include that script on your index page. The reason this isn't working is because your angular app compiles one time, then you load the view and define the controller, but angular doesn't know about that control since it wasn't there when you compiled it.
So:
app.js
angular.module("ibosApp", ["ngRoute", "angular-bootstrap-select"])
.config(function($routeProvider) {
$routeProvider.otherwise({
templateUrl: "/angular/components/booking-system/booking-system-template.html"
});
});
customerCtrl.js
angular.module('ibosApp').controller("customerCtrl", function($scope, $http) {
$scope.loadBrokers = function() {
$http.get("/api/customers/getBrokers").success(function(data) {
$scope.brokers = data;
});
}
$scope.loadBrokers();
}
);
And your markup would be
// previous script tags
<script src="app.js"></script>
<script src="customerCtrl.js"></script>
Is your module only defined in the template? If that's the case that might be your problem, the app isn't initialized since ng-app can't find the module you're trying to load. I would begin with separating JavaScript and HTML to make it easier on yourself.
after watching this presentation (https://www.youtube.com/watch?v=ImR0zo1tA_I) I wanted to try Angular JS. I copied the code, exactly what was on the screen, but i doesn't work. I tried it in my browser, in my page (http://thecodemaker.com.pl), I was doing research about AngularJS but it still doesn`t want to work.
Code :
<!DOCTYPE html>
<html ng-app="basicApp">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/bootstrap.css">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.11/angular.min.js"></script>
</head>
<body ng-controller="TodoController">
<form>
<div class="container">
<div class="panel panel-primary">
<div class="panel-heading">
<h1 class="panel-title"><b>ToDo List</b></h1>
</div>
<ul class="list-group">
<li class="list-group-item" ng-repeat = "todo in todos">
<div class="checkbox">
<label>
<input type="checkbox"> {{todo}}
</label>
<button type="button" class="close">×</button>
</div>
</li>
</ul>
</div>
<div class="form-group has-feedback">
<label class="control-label invisible">Enter Task</label>
<input type="text" class="form-control text-primary"></input>
<button type="button" class="close form-control-feedback text-muted">±</button>
</div>
<div class="alert alert-info">Enter new task to get started</div>
<div class="alert alert-danger">Maximum number of tasks allowed : 5</div>
</div>
</form>
<script src="js/bootstrap.min.js"></script>
<script src="js/jquery-1.11.2.js"></script>
<script>
angular.module("basicApp", [])
.controller("TodoController", ["$scope", function($scope) {
$scope.todos =['Buil an atomic bomb','Sell it on ebay']
}
</script>
</body>
</html>
Any ideas what is wrong ?
There seems to be a lot wrong with your snippet. For one, your submit/add button is not bound to an event listener or anything so it's not doing anything that you'd want (like adding an item to the property on your controller's $scope).
Check out the Todo example on Angular's official website, it's more up to date.
https://angularjs.org/ (scroll down).
Here's the video for it: https://www.youtube.com/watch?v=WuiHuZq_cg4
There is an error : Bootstrap's JavaScript requires jQuery, which means you need to add jQuery library to your project, required by bootstrap.js
Starting with Angular 1.3.x, you can no longer declare a controller as a generic global function on window. Controllers must now use the more current form of component declaration.
<script>
angular.module("basicApp", [])
.controller("TodoController", ["$scope", function($scope) {
$scope.todos =['Buil an atomic bomb','Sell it on ebay']
}
</script>
In the HTML, change ng-app="" to ng-app="basicApp.