Compile an html template with data from my controller - javascript

In Angular,I am building a web app for an hotel that has different rooms. I want to be able to click on a tab in the navbar (or anywhere on the page.) and populate the html view with public data about the room that I have stored in the controller.
what is the best way to go about this? I am using ui-routing. I have yet to find an exhaustive answer on stack overflow.
Below is an example of what my app looks like.
This is my app.js
var appBB = angular
.module('appBB', ['ui.router'])
.config(['$stateProvider', '$urlRouterProvider', MainRouter]);
function MainRouter(states, router) {
states
.state( 'home', {
url:'/',
templateUrl: 'home.html'
}).state( 'show',{
url:'/show',
templateUrl:'show.html'
});
router.otherwise('/');
}
This is my controller
appBB.controller("BBController", BBController());
function BBController() {
var self = this;
self.apartments = [
{
name: "apt1",
image: "imag1.jpg"
amenities: ["blablabal", "bhuhuih", "hvjf"]
},
{
name: "apt2",
image: "img2.jpg",
amenities: ["blablabla", "bkjhkg", "lkhug"]
},
{
name: "apt3",
image: "img3.jpg",
amenities: ["blablabla", "jgfkhgc","jgvkhg"]
}
]
}
This is an example of the view template that I want to fill:
<div ng-controller="BBController as bbs">
<div>
<h4>{{this should show the apt name}}</h4>
</div>
<div class="row">
<div class="col-sm-8">
<img ng-src="{{this should show the image of the apt that i clicked on}}" />
</div>
<div class="col-sm-4">
<ul>
<li ng-repeat="looping over the apt amenities">{{amenity}}</li> </ul>
</div>
</div>
</div>
Any help will be greatly appreciated.

What you are doing looks good but you need some improvement in it.I would suggest you to use $routeParams on Nav-bar clicks. something like:
<div ng-controller="BBController as bbs">
<div>
<h4>{{this should show the apt name}}</h4>
</div>
<div class="row">
<div class="col-sm-8">
<img ng-src="{{this should show the image of the apt that i clicked on}}" />
</div>
<div class="col-sm-4">
<ul>
<li ng-repeat="amemity in amenities">
<a ng-href="#amemityList/{{ amemity.id }}"> {{amemity.name}} </a>
</li>
</ul>
</div>
</div>
Now, you can use this amenity.id to pass to YourController and accordingly fetch respective view with all the info of that "clicked" amenity.id
.when('/amemityList/:navBar', {
templateUrl: "AmenityView.html",
controller: "YourController"
})
In this way, you will be able to use single view AmenityView.html and its info can be as per your amenity.id which has been passed to the controller like
var navBarSelection_id = $routeParams.navBar;

Maybe, you could add the info at the url like /show/apt1 and use apt1 to find the information on the controller.
Edit:
A little explanation: https://docs.angularjs.org/tutorial/step_07

Related

Web Page not Anchoring in Angular

I am attempting to have the page go to a div section of the page based on what they click. I have the div for each section id'd with the proper tag. I have done a test where I can load the page and type url.com/services#insertidhere and it will go to the correct location. The issue is when I try to implement it in the state it won't go to the location. It just goes to the page normally even though the URL shown is correct.
HTML Index Snippet
<div ng-repeat="x in blue.services">
<div class="wrapIMG">
<img src="{{x.icon}}" />
<img class="clone" src="{{x.icon}}" />
</div>
<h4>{{x.title}}</h4>
<hr/>
<p>{{x.text}}</p>
<a ui-sref="services({id: x.title})" class="button2">About This</a>
</div>
myapp.js Snippet
app.config(function($stateProvider){
$stateProvider
.state('index', {
url:"/",
templateUrl: 'main.html',
data: {
cssId: 'home'
}
})
.state('services', {
url: "/services/#:id",
templateUrl: 'services.html',
data: {
cssId: 'services'
}
})
});
Services HTML Snippet
<section class="no-padding" style="" id="[id equal to x.title]"> ...</section>
<section class="no-padding" style="" id="[id equal to x.title]"> ...</section>
<section class="no-padding" style="" id="[id equal to x.title]"> ...</section>
I believe the issue has to be with .state URL but it shows correctly in the URL but it just isn't going to the location.
Angular uses the # in URLs for page routing (so do many other SPA frameworks).
To anchor the link to a specific id on a page, use the $anchorScroll service.
Example:
<div id="scrollArea" ng-controller="ScrollController">
<a ng-click="gotoBottom()">Go to bottom</a>
<a id="bottom"></a> You're at the bottom!
</div>
<script>
angular.module('anchorScrollExample', [])
.controller('ScrollController', ['$scope', '$location', '$anchorScroll',
function($scope, $location, $anchorScroll) {
$scope.gotoBottom = function() {
// set the location.hash to the id of
// the element you wish to scroll to.
$location.hash('bottom');
// call $anchorScroll()
$anchorScroll();
};
}]);
</script>
$scope.toPage = function(){$state.go('index');}
Did you try this?

AngularJS not printing variable

I'm currently building my first single page app with angularJS. The variable information stored in my controller is not displaying on the page. After extensively trying to trouble-shoot this I am at a loss to why it isn't displaying.
<div ng-repeat="x in pers" class="person">
<div class="name">{{ pers.person }}</div>
<div class="out">Out</div>
<div class="in" >In</div>
<div class="onsite">On site</div>
<div class="notes">
<div class='n'></div>
<div class='dn'>Delete note</div>
<div class='an'>Add note</div>
</div>
My controller looks like this.
app.controller("MainController", ['$scope', function($scope) {
$scope.pers = [
{
person: 'Nick',
},
{
person: "Greg",
}];
}]);
The repeat function works as expected and two tables are formed, however both the divs with the class name are left without any text in them on the page. I have tried using ng-binding="pers.person" as well without any success.
Thanks in advance for any help you can offer with this issue I'm having.
it should be {{x.person}}
you are using ng-repeat of pers with the alias x

Loading route into dynamically named view?

I'm trying to build accordion style navigation for an app with Meteor and Angular JS. I have a list of articles like so:
State:
$stateProvider
.state('articles', {
url: '/articles',
template: '<articles></articles>'
});
<articles>:
<div class="article-entry" ng-repeat="article in articles.list" slug="{{article.slug}}">
<div class="inner">
//...
<div ui-view="{{article.slug}}"></div>
<a ui-sref="article.content({slug: article.slug})">View article</a>
</div>
</div>
And then the article content:
$stateProvider
.state('articles.content', {
url: '/:slug',
template: '<content></content>'
});
<content> is just, you guessed it, the article content.
Is it possible to get <content> to show up in the ui-view associated with it when someone visits the articles.content state? How would I do this?

Nested Angular Controllers and Views management

I guess it is best to describe it with a picture. I have an angular app and here is a simple view.
Obvious explanation: list shows all the entities, if you click on an entity you can edit it in the form that is hidden by default and similar action applies to adding a new entity.
the issue
I know it is basic example so here the solution might be an overkill but I want to separate the logic of 'Add new entity', 'Edit entity' and 'Entities list'. I thought I could implement it like this:
<div ng-include="'userAddForm.html'"
ng-show="???"
ng-controller="AddUser as add">
</div>
<div ng-include="'userEditForm.html'"
ng-show="???"
ng-controller="AddEdit as edit">
</div>
<div class="panel panel-default">
... list managed by the current controller
</div>
What I miss
I have a difficulty in sharing a state of the hidden parts. For example some boolean flag. For instance:
Click on the entity shows the edit form
Save/Cancel in the edit form hides the part
Then, I think the first step is the responsibility of list-controller, but save/cancel part goes to edit-controller. It would be only possible to share the value with a service included in both - but that does not seem reasonable either.
I think there is some simple solution I can not see and I am open for any advice. Thanks!
If your goal is a simple solution with just a boolean being toggled in the model, you can use child controllers like this:
http://plnkr.co/edit/P1ncToJwqvxt9F9MTF5E?p=preview
The child controllers will inherit the scope of the parent controller and can directly edit the values. I have the edit child controller filtering for editMode==true, so when the parent changes that value, the child controller automatically shows the item. All changes are updated live and the child controller simply toggles the editMode property to remove it from the editing area.
Similar logic is used for the add child controller.
The views look like this:
index.html
<div ng-controller="myCtrl">
<div ng-controller="addCtrl" ng-include="'userAddForm.html'">
</div>
<div ng-controller="editCtrl" ng-include="'userEditForm.html'">
</div>
<h1>Listing</h1>
<ul>
<li ng-repeat="item in items | filter:{addMode:false}">
{{item.id}}
{{item.name}}
<button ng-click="startEditing(item)">[ edit ]</button>
</li>
</ul>
<button ng-click="startAdding()">[ add ]</button>
<div>Debug:<br>{{items}}</div>
</div>
userAddForm.html
<ul>
<li ng-repeat="item in items | filter:{addMode:true}">
<input type="text" ng-model="item.id">
<input type="text" ng-model="item.name">
<button ng-click="add(item)">[ add ]</button>
<button ng-click="cancel(item)">[ cancel ]</button>
</li>
</ul>
userEditForm.html
<ul>
<li ng-repeat="item in items | filter:{editMode:true}">
<input type="text" ng-model="item.id">
<input type="text" ng-model="item.name">
<button ng-click="save(item)">[ save ]</button>
</li>
</ul>
And the controllers look like this:
angular.module('myApp.controllers',[])
.controller('addCtrl', function($scope) {
$scope.add = function(item) {
item.addMode = false;
}
$scope.cancel = function(item) {
$scope.items.pop(item);
}
})
.controller('editCtrl', function($scope) {
$scope.save = function(item) {
item.editMode = false;
}
})
.controller('myCtrl', function($scope) {
$scope.items = [
{name:'aap', id:"1", editMode:false, addMode:false},
{name:'noot', id:"2", editMode:false, addMode:false},
{name:'mies', id:"3", editMode:false, addMode:false},
{name:'zus', id:"4", editMode:false, addMode:false}
];
$scope.startAdding = function(){
$scope.items.push({addMode:true});
};
$scope.startEditing = function(item){
item.editMode = true;
};
});
You can achieve this using Angular state routing.In which you will create state (different views) like -
header
addEntity
editEntity
listEntity
refer https://github.com/angular-ui/ui-router/wiki/Nested-States-%26-Nested-Views
Sharing state can be implemented by creating a service which is than injected to all interested párties (controllers), service can hold data which controllers can be bound to and display in template. Services in Angular JS are singletons so all the controllers are accesing and mutating shared state.

In Angular ui-router nested state url changes,but template is not loading

I am using ui-router for nested states & views. When I click on the link, the URL changes to the URL for the substate, but the template does not load.
For example, when the URL changes to the substate project/settings, the corresponding template project.settings.html is not loading.
Here is an SSCCE courtesy of Plunkr
Below is my code as well:
app.js
myApp.config(function ($stateProvider, $urlRouterProvider){
$stateProvider
.state('project', {
url: "/project",
views:{
"content":{templateUrl: "partials/project.html"},
"header":{templateUrl: "partials/header"}
}
})
.state('project.settings', {
url: "/settings",
views:{
"content":{templateUrl: "partials/project.settings.html"},
"header":{templateUrl: "partials/header"}
}
})
$urlRouterProvider.otherwise("/")
});
/* cheching whether the user is authentic or not*/
myApp.run(function($rootScope,$location,$cookieStore,validateCookie,$state) {
$rootScope.$on('$stateChangeStart',function(event,toState,toParams,fromState){
if($cookieStore.get('user')){
validateCookie.authService(function(result,error){
if(!result){
$location.path("/");
}else{
$state.go('project.settings');
}
});
}
else{
$location.path("/");
}
});
});
index.html
<div ng-controller="userController">
<div ui-view="header"></div>
<div class="container" ui-view="content"></div>
</div>
project.html
<div ng-controller="userController">
<div class="details">
<a ui-sref=".settings" class="btn btn-primary">Settings</a>
</div>
</div>
project.settings.html
<h1>Project Setting -State test</h1>
Your nested project.settings state needs to address the view in the higher state explicitly using an '#' suffix, ie.:
.state('project.settings', {
url: "/settings",
views:{
"content#":{templateUrl: "partials/project.settings.html"},
"header#":{templateUrl: "partials/header"}
}
})
See more details here https://github.com/angular-ui/ui-router/wiki/Multiple-Named-Views#view-names---relative-vs-absolute-names
First of all change file name project.settings.html in templateurl and file name to projectSettings.html (remove dot).
.state('project.settings', {
url: "/settings",
views:{
"content":{templateUrl: "partials/projectSettings.html"},
"header":{templateUrl: "partials/header"}
}
})
Add two divs in the project template to load the sub pages (header abd projectSettings)
Note: Any content in this divs will be replaced with the page loaded here.
project.html
<div ng-controller="userController">
<div class="details">
<a ui-sref=".settings" class="btn btn-primary">Settings</a>
</div>
<div ui-view="header">( Project Page header will replace with projectSettings header )</div>
<div class="container" ui-view="content">( Project Page content will replace with projectSettings Content )</div>
</div>
I had the same issue and the solution was to place ui-view to your parent's template. Because your partials also need a too, if they will be loading a template from a child state.
See here https://github.com/angular-ui/ui-router/wiki/Frequently-Asked-Questions#issue-my-templates-are-not-appearing--loading--showing
If using nested views with UI-router, be sure to add ui-view into the html of the parent page and include specific named views.
I had the same issue, the solution was; open the project.html file (which is the parent page) and wrap everything within <ui-view>
So, replace these:
<div ng-controller="userController">
<div class="details">
<a ui-sref=".settings" class="btn btn-primary">Settings</a>
</div>
</div>
with these:
<ui-view>
<div ng-controller="userController">
<div class="details">
<a ui-sref=".settings" class="btn btn-primary">Settings</a>
</div>
</div>
</ui-view>
and you will be good to go ;)
Use ui-sref="project.settings" for link in project.html template.

Categories

Resources