Angular.js template won't show on angular-route url - javascript

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.

Related

Script static fallback content for Angular $http request

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.

Is this possible using only angular-formly?

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 :)

scope values are not getting display in the view

I am new to AngularJS. I stored the response data in the scope in my controller . But the values stored in scope not getting displayed in the html page.
guest-controller.js
var guestProfileApp = angular.module('guestProfileApp', ['guestProfileServices' ]);
guestProfileApp.controller( 'guestProfileController', [ '$scope', 'guestProfileService', GuestProfileController ]);
function GuestProfileController( $scope, guestProfileService)
{
$scope.getProfile = getProfile;
$scope.saveProfile = saveProfile;
console.log('guest profile controller called');
function getProfile( profileID ){
return guestProfileService.getProfile( profileID ).then( function( response ){
$scope.profileBizObj = response.data;
console.log($scope.profileBizObj);
window.location = "profile.html";
});
}
}
profile.html
<html lang="en" ng-app="guestProfileApp">
<body ng-controller="guestProfileController">
<div class="form-group">
<div class="input-group">
<input type="text" class="form-control" placeholder="First Name" id="f_firstName" ng-model="profileBizObj.profileData.nameInfo.firstName">
<div class="input-group-addon"><span class="glyphicon glyphicon-user"></span></div>
</div>
</div>
<div class="form-group">
<div class="input-group">
<input type="text" class="form-control" placeholder="Last Name" id="f_lastName" ng-model="profileBizObj.profileData.nameInfo.lastName">
<div class="input-group-addon"><span class="glyphicon glyphicon-user"></span></div>
</div>
</div>
<div class="form-group">
<div class="input-group">
<input type="date" class="form-control" placeholder="Date of Birth" id="f_dob" ng-model="profileBizObj.profileData.nameInfo.birthDate">
<div class="input-group-addon"><span class="glyphicon glyphicon-gift"></span></div>
</div>
</div>
</body>
</html>
When I displayed the response data using
console.log($scope.profileBizObj);
The data is displaying correctly. But when I am moving to "profile.html" and trying to display the profileBizObj data using ng-model the values are not getting displayed.
Here is the output of console.log($scope.profileBizObj);
{"addressList":[],
"customerID":"MYCUST",
"emailList":[],
"formattedName":"JOHN PAWLIW, #388569330",
"phoneList":[],
"profileData":{"createdOn":"2015-11-24T14:05:58",
"customerID":"MYCUST",
"nameInfo":{"createdOn":"2015-11-24T14:05:58",
"firstName":"JOHN",
"lastName":"JOHN PAWLIW",
"mergedObjectState":2,
"middleName":"",
"nameInfoID":12642,
"nameTitle":"MR",
"profileID":7183,
"selectedLocale":"en_US",
"updatedOn":"2015-11-24T14:05:58"},
"profileID":7183,
"selectedLocale":"en_US",
"status":"ACTIVE",
"updatedOn":"2015-11-24T14:05:58"},
"profileID":7183,
}
Please help me as how to resolve this issue . Thank You
In order to display the $scope.profileBizObj in view.html. You can use ng-repeatto iterate through object properties.
<div ng-repeat="item in profileBizObj">
<div class="form-group">
<div class="input-group">
<input type="text" class="form-control" placeholder="First Name" id="f_firstName" ng-model="item.profileData.nameInfo.firstName">
<div class="input-group-addon"><span class="glyphicon glyphicon-user"></span></div>
</div>
<div class="form-group">
<div class="input-group">
<input type="text" class="form-control" placeholder="Last Name" id="f_lastName" ng-model="item.profileData.nameInfo.lastName">
<div class="input-group-addon"><span class="glyphicon glyphicon-user"></span></div>
</div>
</div>
</div>
This is the fiddle link: https://jsfiddle.net/rrwfu834/2/
window.location = "profile.html"
loads a new page. The new page shares no information with the previous page. It's like hitting reload or typing a new url into the browser window.
Looking at your code, simply try removing that line to see if resolves your issue.
There are several ways to load a template within the current page - the easiest of which is probably ng-include.
You can also use routes or ui.router.
The issue is resolved by making following changes
profiletest.html
<body>
<div ng-app="guestProfileApp">
<div ng-controller="guestProfileController">
<button ng-click="getProfile(1546)">Show Profile</button>
<ng-include ng-if="showProfile" src="'profile1.html'"></ng-include>
</div>
</div>
</body>
guest-controller.js
function GuestProfileController( $scope, guestProfileService)
{
$scope.getProfile = getProfile;
$scope.saveProfile = saveProfile;
console.log('guest profile controller called');
function getProfile( profileID ){
return guestProfileService.getProfile( profileID ).then( function( response ){
$scope.showProfile = true;
$scope.profileBizObj = response.data;
});
}
}

Javascript Remove a Template Element

I have a template that I will simplify as follows:
<script type="text/template" id="contactTemplate">
<div id="contactentry" class="row contact-info">
</div>
<div class="form-group">
<label for="name1">First Name</label>
<input type="text" class="form-control" id="FirstName" name="Contacts[{{ID}}].FirstName" required>
</div>
<div class="form-group minus">
<label for="contactMinus{{ID}}"> </label>
<a id="depminus{{ID}}"><i class="fa fa-minus-circle"></i>Remove</a>
</div>
</script>
I allow insertion of the template, multiple times via the following code, this part works:
<script type="text/javascript">
var clone = (function () {
var cloneIndex = -1;
var template = $('#contactTemplate').text();
return function () {
//Replace all instances of {{ID}} in our template with the cloneIndex.
return template.replace(/{{ID}}/g, ++cloneIndex);
}
})();//self executing function.
var contacts = $('#contacts')
$("#contactadd").on("click", function () {
contacts.append(clone());
window.controlManager.FindControls(contacts);
});
</script>
<div id='contacts'>
<div class="col col-lg-1">
<a id="contactadd"><i class="fa fa-plus-circle"></i>Add</a>
</div>
</div>
Now I am trying to figure out how to make javascript code to remove each element when/if the minus button is clicked (in the template).
I'm not sure what kindof code I could then use to delete the contacts, via the depminus{{ID}} control. Any tips to get me started?

Angular Dependency Injection, Passing values between modules using service

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"]);

Categories