I have read about the dependency injection in angular. I thought to test it. But as I inject the module, I want to pass the values from one module to another (I am outputting on console
(Edit: Solved it is giving error. Uncaught Error: No module: sisUser angular.min.js:18 It is not even evaluating the angular expression {{2+2}})
Let me explain the scenario:
Login.html
Plain simple Login for asking for two text input username and password into a service "user".
<html lang="en" ng-app="wbsislogin">
<head>
</head>
<body>
<form>
<fieldset>
<label>
<span class="block input-icon input-icon-right">
<input type="text" class="span12" ng-model="username" placeholder="Username" />
<i class="icon-user"></i>
</span>
</label>
<label>
<span class="block input-icon input-icon-right">
<input type="password" class="span12" ng-model="password" placeholder="Password" />
<i class="icon-lock"></i>
</span>
</label>
<div class="space"></div>
<div class="clearfix">
<label class="inline">
<input type="checkbox" class="ace" />
<span class="lbl"> Remember Me</span>
</label>
<button ng-click="loginbtn()" class="width-35 pull-right btn btn-small btn-primary">
<i class="icon-key"></i>
Login
</button>
</div>
<div class="space-4"></div>
</fieldset>
</form>
<script src="angular/angular.min.js"></script>
<script src="wbsis.js"></script>
</body>
</html>
Dash.html
Showing just the passed username and password from login.html through the injected service
<html lang="en" ng-app="wbsislogin">
<head>
</head>
<body>
<p>{{2+2}}</p>
<div ng-controller="ditest">
{{ usen }} {{ pasw }}
</div>
<script src="angular/angular.min.js"></script>
<script src="wbsis.js"></script>
</body>
</html>
wbsis.js
var sisUser = angular.module("wbsislogin",[]);
var wbSis = angular.module("wbsis",["wbsislogin"]); // as per the solution 1
sisUser.controller("loginformCtrl",function($scope,user,$log,$location){
$scope.username = "s";
$scope.password = "test2";
$scope.loginbtn = function(){
user.usern = $scope.username;
user.passw = $scope.password;
$log.log(user.usern,user.passw);
window.location.href='http://sis_frnt.dev/app/dash.html';
}
});
sisUser.factory("user", [function($log){
var user = {
usern: '',
passw: ''
};
return user;
}]);
wbSis.controller("ditest", function($scope, $log, user){
$log.log(user.usern,user.passw);
$scope.usen = user.usern;
$scope.pasw = user.passw;
})
Please guide where I am doing wrong.
You need to pass the name of the module as a dependency instead of the variable name.
Change:
var sisUser = angular.module("wbsislogin",[]);
var wbSis = angular.module("wbsis",["sisUser"]);
To:
var sisUser = angular.module("wbsislogin",[]);
var wbSis = angular.module("wbsis",["wbsislogin"]);
Related
I have used the error form validation in the addnewstudent page as below and it's working fine.
<td>
<input limit-to="50" type="email" name="input" ng-model="Email" />
<span style="display:none">{{ emailValid = !!myForm.$error.email}}</span>
<span ng-class="customStyle.colorClass">
{{EmailValidation }}
</span>
</td>
Same approach I used for my edit page as like below, but Iam not able to get the bool value of "!!myForm.$error".
my Edit page
<td>
<input limit-to="50" type="text" ng-model="Student.email" />
<span style="display:none">{{ emailValid = !!myForm.$error.Student.email}}
</span>
<span>
{{EmailValidation }}
</span>
</td>
My JS,
$scope.save = function () {
if ($scope.emailValid || $scope.Student.email=='') {
$scope.EmailValidation = 'Not a valid email (ex: me#example.com)';
return;
}
else {
$scope.EmailValidation = '';
}
.......
.......
Where I did go wrong on my edit page?
To validate a form input in angularjs there should be name attribute for that input and form also.
angular.module('sampleApp', [])
.controller('myCtrl', function($scope) {
$scope.Student = {}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="sampleApp" ng-controller="myCtrl" >
<form name="myForm" novalidate>
<input limit-to="50" type="email" ng-model="Student.email" name="email" required/>
<div ng-show="myForm.$submitted || myForm.email.$touched">
<span ng-show="myForm.email.$error.required">Tell us your email.</span>
<span ng-show="myForm.email.$error.email">This is not a valid email.</span>
</div>
<button>Submit</button>
</form>
</div>
Above code will check for non empty valid email, which is done by required,type="email" attributes.
I am not able to see error message on clicking the submit button using angularjs.
Any lead will be appreciated
Thanks in advance :)
<form id="formbody" ng-submit="submituser(form)" name="form" novalidate>
<input type="text" ng-class="{ errorinput: submitted && form.dob.$invalid }" name="dob" ng-model="dob" placeholder="Date of Birth" required />
<span class="e" ng-show="submitted && form.dob.$invalid">Please provide a valid date of birth</span>
<div style="padding-left: 275px;">
<button type="submit">Submit</button>
<!-- <div type="button" id="btn" style="color: red;" >Submit</div> -->
</div>
</div>
</form>
.controller('ExampleController', function($scope, $location, $scope, $stateParams) {
$scope.singleSelect = '';
$scope.goToPage = function() {
console.log("selectservice");
$location.path("/selectservice");
}
$scope.submituser = function($scope) {
if ($scope.form.$valid) {} else {
$scope.submitted = true;
}
}
})
change ng-show of span to
<span class="e" ng-show="submitted && form.dob.$invalid">Please provide a valid date of birth</span>
please check the form name
you have used two different names
name ="form" in form tag and used as signUpForm.dob in input field.
Check your ng-model to
<form id="formbody" ng-submit="submituser(form)" name="signUpForm" novalidate>
<input type="text" ng-class="{ errorinput: submitted && signUpForm.dob.$invalid }" name="dob" ng-model="form.dob" placeholder="Date of Birth" required />
<span class="e" ng-if="submitted && signUpForm.dob.$invalid">Please provide a valid date of birth</span>
<div style="padding-left: 275px;">
<button type="submit">Submit</button>
</div>
</div>
</form>
.controller('ExampleController',function($scope,$location,$scope, $stateParams){
$scope.singleSelect='';
$scope.goToPage=function(){
console.log("selectservice");
$location.path("/selectservice");
}
$scope.submitted =false;
$scope.submituser = function(form){
// console.log(form);
if (form.$valid) {
your logic
} else {
$scope.submitted = true;
}
}
})
Try something like that
<link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="form" ng-app>
<div class="control-group" ng-class="{true: 'error'}[submitted && form.dob.$invalid]">
<label class="control-label" for="dob">Your Date of Birth</label>
<div class="controls">
<input type="text" name="dob" ng-model="dob" required />
<span class="help-inline" ng-show="submitted && form.dob.$invalid">Please provide a valid date of birth</span>
</div>
</div>
<button type="submit" class="btn btn-primary btn-large" ng-click="submitted=true">Submit</button>
</form>
You have to provide the form name but even after that you cannot refer to your form in controller unless you pass it through the submit function arguments. Also there is not signupForm() function in your controller.
The way to go is :
<form id="formbody" name="myForm" ng-submit="signupForm(myForm)" novalidate>
<!-- inputs etc -->
</form>
Then based on submituser():
$scope.signupForm = function(myForm) {
//Do whatever you want to do
if(myForm.$valid) {
//some logic
}else {
$scope.submitted = true;
}
}
On the other hand if you don't want to mess up with the controller you can always use FormController method $submitted. This would look like:
<span class="e" ng-show="myForm.$submitted && myForm.dob.$invalid">Please provide a valid date of birth</span>
I've built a basic Angular app that successfully displays the results of an HTTP GET request.
I'd like to include fallback code that displays two static HTML elements in place of the remote content if the GET request fails.
I can just call a vanilla JS function to do DOM manipulation, but I'd like to do this the Angular way. I've read a lot of documentation and articles, but I'm not seeing a straightforward way to do this. Code below.
I'd like to replace the call to updateUIError() with Angular code that performs the same task.
Here's a Plunk: https://plnkr.co/edit/PDwSUCXGNW2cwAIwl9Z9?p=streamer
HTML:
<div class="scene fullheight" id="attractions" ng-app="listApp">
<article class="content">
<h1>Upcoming Events</h1>
<div class="main" ng-controller="ListController as eventsList">
<div class="search">
<label>search: </label>
<input ng-model="query" placeholder="Search for events" autofocus>
<label class="formgroup">by:
<select ng-model="eventOrder" ng-init="eventOrder='start.local'">
<option value="start.local">Date</option>
<option value="name.text">Name</option>
</select>
</label>
<label class="formgroup">
<input type="radio" ng-model="direction" name="direction" checked>
ascending
</label>
<label class="formgroup">
<input type="radio" ng-model="direction" name="direction" value="reverse">
descending
</label>
</div>
<ul class="eventlist">
<li class="event cf" ng-repeat="item in eventsList.events | filter: query | orderBy: eventOrder:direction">
<div class="info">
<h2>{{item.name.text}}</h2>
<p>{{item.start.local | date:"dd MMMM ', ' h:mma"}}</p>
</div>
</li>
</ul>
</div>
</article>
</div>
Angular:
angular.module('listApp', [])
.controller('ListController', ['$scope', '$http', function($scope,$http) {
var eventsList = $scope.eventsList;
$http.get(URI)
.success(function(data) {
console.log(data);
eventsList.events = data.events;
}).error(function() {
updateUIError();
});
}]);
function updateUIError() {
var events = document.querySelector('#attractions article');
events.innerHTML = '<h1>Local Attractions</h1><p>There's lots to do nearby.</p>';
}
You need to create a static error and show it when the error occurs using ngIf
<div class="scene fullheight" id="attractions" ng-app="listApp">
<div ng-controller="ListController">
<article class="content" ng-if="hasUIError">
<h1>Local Attractions</h1>
<p>There's lots to do nearby.</p>
</article>
<article class="content" ng-if="!hasUIError">
<h1>Upcoming Events</h1>
<!-- REST OF THE HTML -->
</article>
</div>
</div>
Then, in your controller, you need to set the flag to false by default:
$scope.hasUIError = false;
And when there's an error in the ajax, set it to true
$http.get(URI).then(
function(response) {
console.log(response);
$scope.events = response.data.events;
},
function() {
$scope.hasUIError = true;
}
);
Before solving your issue, there is another issue to address. Specifically, since you are using the ControllerAs approach, you'll want to attach your variables to 'this' rather than $scope.
Then you create a variable called showError that will get evaluated in showing the message. Then you can use the ng-show directive to hide/show the message.
angular.module('listApp', [])
.controller('ListController', ['$http',
function($http) {
var vm = this;
vm.events = [];
vm.showError = false;
$http.get(URI)
.success(function(data) {
vm.events = data.events;
}).error(function() {
vm.showError = true;
});
}
]);
<!DOCTYPE html>
<html ng-app="listApp">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>
document.write('<base href="' + document.location + '" />');
</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js#1.5.x" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.10/angular.min.js" data-semver="1.5.10"></script>
<script src="app.js"></script>
</head>
<body ng-controller="ListController as eventsList">
<div class="scene fullheight" id="attractions">
<div ng-show="eventsList.showError">
<h1>Local Attractions</h1>
<p>There's lots to do nearby.</p>
</div>
<article class="content">
<h1>Upcoming Events</h1>
<div class="main">
<div class="search">
<label>search:</label>
<input ng-model="query" placeholder="Search for events" autofocus>
<label class="formgroup">by:
<select ng-model="eventOrder" ng-init="eventOrder='start.local'">
<option value="start.local">Date</option>
<option value="name.text">Name</option>
</select>
</label>
<label class="formgroup">
<input type="radio" ng-model="direction" name="direction" checked>ascending
</label>
<label class="formgroup">
<input type="radio" ng-model="direction" name="direction" value="reverse">descending
</label>
</div>
<ul class="eventlist">
<li class="event cf" ng-repeat="item in eventsList.events | filter: query | orderBy: eventOrder:direction">
<div class="info">
<h2>{{item.name.text}}</h2>
<p>{{item.start.local | date:"dd MMMM ', ' h:mma"}}</p>
</div>
</li>
</ul>
</div>
</article>
</div>
</body>
</html>
Do something like this:
angular.module('listApp', [])
.controller('ListController', ['$scope', '$http', function($scope,$http) {
var eventsList = $scope.eventsList;
$http.get(URI)
.success(function(data) {
console.log(data);
eventsList.events = data.events;
}).error(function() {
eventsList.errorMessage = '<h1>Local Attractions</h1><p>There's lots to do nearby.</p>';
});
}]);
In the HTML, add a span inside the scope of ListController that will have ngModel="errorMessage". You can add additional property to show / hide the error span and main content div.
I am trying to learn angular.js and I want to load a form html through angular-route with a template.
I think I set up everything correctly, but the html form won't load on the url that I set on config. And the other config url I set up for testing won't work either.
Here is the code
index.html
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" href="/bower_components/bootstrap/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="/css/style.css">
</head>
<body ng-app="EventPlanner">
<div ng-view></div>
</body>
</html>
<script type="text/javascript" src="/bower_components/angular/angular.min.js"></script>
<script type="text/javascript" src="/bower_components/angular-route/angular-route.min.js"></script>
<script type="text/javascript" src="/js/angular/ng_config.js"></script>
<script type="text/javascript" src="/js/angular/ng_controller.js"></script>
ng_config.js
angular.module("EventPlanner", ["ngRoute"])
.config(["$routeProvider", function($routeProvider){
$routeProvider.when("/", {
templateUrl: "template/register.html"
})
.when("/make_plan", {
template: "<h1>make plans</h1>"
});
}]);
ng_controller.js
angular.module("EventPlanner", [])
.controller("registerControl", [function(){
var self = this;
self.submit = function(){
location.href = "#/make_plan";
};
}]);
register.html
<div class="main container">
<div class="row" ng-controller="registerControl as regi">
<form ng-submit="regi.submit()" name="regiForm" class="register col-xs-12">
<label class="col-xs-12" for="name">
<span class="col-xs-2">Name</span>
<input ng-model="regi.username" class="col-xs-5" type="text" id="name" name="name" required>
<span class="col-xs-5" ng-show="regiForm.name.$error.required">This feild is required</span>
</label>
<label class="col-xs-12" for="email">
<span class="col-xs-2">Email</span><input ng-model="regi.email" class="col-xs-5" type="email" id="email" name="email" required>
<span class="col-xs-5" ng-show="regiForm.email.$error.required">This feild is required</span>
</label>
<label class="col-xs-12" for="birthday">
<span class="col-xs-2">Birthday</span><input ng-model="regi.birthday" class="col-xs-5" type="date" id="birthday">
</label>
<label class="col-xs-12" for="password">
<span class="col-xs-2">Password</span>
<input ng-model="regi.password" class="col-xs-5" type="password" id="password" name="password"
ng-pattern="/^(?=.*[0-9])(?=.*[!##$%^&*])[a-zA-Z0-9!##$%^&*]{6,16}$/" ng-minlength="6" ng-maxlength="16" required>
</label>
<ul class="col-xs-7">
<li class="col-xs-12" ng-show="regiForm.password.$error.pattern">Must contain one lower & uppercase letter, and one non-alpha character (a number or a symbol.)</li>
<li class="col-xs-12" ng-show="regiForm.password.$error.minlength">Password Must be more than 5 characters</li>
<li class="col-xs-12" ng-show="regiForm.password.$error.maxlength">Password Must be less than 20 characters</li>
<li class="col-xs-12" ng-show="regiForm.name.$dirty && regiForm.name.$error.required">Please enter name
</li>
</ul>
<div class="col-xs-7 no-padding">
<button type="submit" ng-disabled="regiForm.$invalid" class="btn">Submit</button>
</div>
</form>
</div>
I have been looking at the code over and over for past few days, I cannot figure out what I did wrong.
Please help.
Thank you.
You have an error in your code.
ng_config.js
angular.module("EventPlanner", ["ngRoute"]) // correct!
.config(["$routeProvider", function($routeProvider){
$routeProvider.when("/", {
templateUrl: "template/register.html"
})
.when("/make_plan", {
template: "<h1>make plans</h1>"
});
}]);
The above is correct, you are defining a new module 'EventPlanner' and defining an array of dependencies.
ng_controller.js
angular.module("EventPlanner", []) // incorrect!!
.controller("registerControl", [function(){
var self = this;
self.submit = function(){
location.href = "#/make_plan";
};
}]);
The above is incorrect. You do not need to pass an empty array anymore as you have already created your module 'EventPlanner'.
What is actually happening above is you are redefining the module 'EventPlanner' and overwriting your previous declaration.
Change ng_controller.js to the following:
angular.module("EventPlanner") // fixed
.controller("registerControl", [function(){
var self = this;
self.submit = function(){
location.href = "#/make_plan";
};
}]);
Now, when ng_controller.js is parsed, it tells angular that it wishes to create a 'registerController' for a previously defined module called 'EventPlanner'. Hope that makes sense.
So, I have this form, made using AngularJS here, which basically lets me create a purchase object to send to a server, i.e, it lets me select a store where I bought some items, set a "date of purchase" (just a text field for now), and add those items to the object I'm gonna send.
After the submit button it is shown how the model I'm going to send will look like, showing the id of the store, the "datetime", and an array of items.
My question is: Is there a way of doing this form using angular-formly only?
The question arises because I've been reading formly's docs and I haven't figured out how to make it create such a dynamic model as this form does, i.e., with a variable-length array of items of the purchase, or if it is at all possible.
Thanks in advance for any clue you can give me to answer this question :)
The code for the form is as follows:
(function(){
var app = angular.module('test', []);
})();
The html page:
<!DOCTYPE html>
<html>
<head>
<link type="text/css" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.css"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.5/angular.js"></script>
<script src="inab.js"></script>
<script src="PurchaseCtrl.js"></script>
</head>
<body ng-app="test">
<div ng-controller="PurchaseCtrl" class="col-md-4">
<h2>Purchase</h2>
<div class="panel panel-default">
<div class="panel-heading">Title</div>
<div class="panel-body">
<div class="form-group">
<label>Store</label>
<select class="form-control" ng-model="model.store">
<option ng-repeat="store in stores" value="{{store.id}}">{{store.name}}</option>
</select>
</div>
<div class="form-group">
<label>date-time</label>
<input class="form-control" type="text" ng-model="model.datetime"/>
</div>
<div ng-repeat="item in items">
<div class="form-group">
<div class="col-sm-2">
<label>{{item.label}}</label>
</div>
<div class="col-sm-8">
<input class="form-control" type="text" ng-model="item.nome" />
</div>
<div class="col-sm-2">
<button type="submit" class="btn btn-alert submit-button col-md-2" ng-click="removeItem()">remove item</button>
</div>
</div>
</div>
<button ng-click="addItem()">Add item</button>
</div>
</div>
<button type="submit" class="btn btn-primary submit-button" ng-click="onSubmit()">Submit</button>
<pre>{{model | json}}</pre>
</div>
</body>
</html>
The controller:
(function(){
angular.module('test').controller('PurchaseCtrl', ['$scope', function(scope){
scope.stores = [{id: 1, name:'Store 1'}, {id: 2, name: 'Store 2'}];
scope.items = [];
scope.datetime = '';
scope.store = '';
var i = 0;
scope.model = {
store: scope.store,
datetime: scope.datetime,
items: scope.items
};
scope.addItem = function(){
scope.items.push({label: 'algo' + (i++), nome:''});
}
scope.removeItem = function(){
scope.items.splice(scope.items.length - 1);
}
scope.onSubmit = function(){
console.log(scope.model);
}
}]);
})();
As #Satej commented, it was with repeated sections. Thanks :)