How to implement multiple ng controllers with http calls in AngularJS? - javascript

In an app / on a page I have several places, where data should be loaded asynchronously. E.g.: a DIV with images and another one with cateories (for the navi). I implement it like this:
app.js
(function() {
var app = angular.module('portfolio', []);
app.controller('ProjectsListController', ['$http', function($http) {
var projectsList = this;
projectsList.projectsListData = [];
$http.get(config['api_server_url'] + '/projects').success(function(data) {
projectsList.projectsListData = data;
});
}]);
app.controller('NaviCategoriesController', ['$http', function($http) {
var categoriesList = this;
categoriesList.categoriesListData = [];
$http.get(config['api_server_url'] + '/categories').success(function(data) {
categoriesList.categoriesListData = data;
});
}]);
})();
list.phtml
<!-- projects -->
<div id="projects" ng-app="portfolio">
<div id="projectsList" ng-controller="ProjectsListController as projectsList">
<div class="projectItem" ng-repeat="projectItem in projectsList.projectsListData._embedded.projects">
<div class="project-image">
<img
ng-src="{{projectItem._embedded.images[0].src}}"
title="{{projectItem.title}} - {{projectItem._embedded.images[0].title}}"
alt="{{projectItem.title}} - {{projectItem._embedded.images[0].title}}"
/>
</div>
</div>
</div>
</div>
navi-categories .phtml
<!-- navi-categories -->
<div id="navi-categories" ng-app="portfolio">
<ul id="categoriesList" ng-controller="NaviCategoriesController as categoriesList">
<li class="categoryItem" ng-repeat="categoryItem in categoriesList.categoriesListData._embedded.categories">
{{categoryItem.short_name}}
</li>
</ul>
</div>
Every of these two blocks works fine. But I cannot use both at the same time. That means: The categories only get displayed, when the projects/images list is commented out (in the HTML) -- when I activate the list, the categories' HTTP request doesn't get sent anymore.
What am I doing wrong? How to implement this correctly?

Well... the problem is that they both have the ng-app="portfolio". You should wrap both components in one div with the ng-app="portfolio" attribute:
<div id="app" ng-app="portfolio">
<div id="projects">
<div id="projectsList" ng-controller="ProjectsListController as projectsList">
<div class="projectItem" ng-repeat="projectItem in projectsList.projectsListData._embedded.projects">
<div class="project-image">
<img
ng-src="{{projectItem._embedded.images[0].src}}"
title="{{projectItem.title}} - {{projectItem._embedded.images[0].title}}"
alt="{{projectItem.title}} - {{projectItem._embedded.images[0].title}}"
/>
</div>
</div>
</div>
</div>
<div id="navi-categories">
<ul id="categoriesList" ng-controller="NaviCategoriesController as categoriesList">
<li class="categoryItem" ng-repeat="categoryItem in categoriesList.categoriesListData._embedded.categories">
{{categoryItem.short_name}}
</li>
</ul>
</div>
</div>

Related

Passing data using Handlebars.js

I've created a basic app to test out handlebars.js and I'm struggling to pass data between my pages. What I want is to have a list of countries being read from a JSON file, then the user can click on a country to be taken to more detail. The data loads fine on the first page but then when I click onto the link, it takes me to the next page were the data isn't loading in.
Could someone explain where I'm going wrong?
First page:
<div data-page="countrylist" class="page">
<div class="page-content">
<div class="content-block-title">Choose a country:</div>
<div class="list-block">
<ul>
{{#each this}}
<li>
<a href="detail.html" class="item-content item-link" data-context-name="countrylist.{{#index}}​">
<div class="item-inner">
<div class="item-title">{{Country}}​</div>
</div>
</a>
</li>
{{/each}}
</ul>
</div>
</div>
</div>
Detailed page:
<div data-page="countrylist" class="page">
<div class="page-content">
<div class="content-block inset">
<div class="content-block-inner">
<h3>{{Country}}​</h3>
<ul>
<li>Region: {{Region}}</li>
<li>Population: {{Population}}</li>
<li>Area Sq. Mile: {{AreaSqMile}}</li>
<li>Population Density per sq. Mile: {{PopulationDensity}}</li>
<li>NetMigration: {{NetMigration}}</li>
<li>GDP $ per capita: {{GDP}}</li>
<li>Phones per 1000: {{Phones}}</li>
<li>Arable %: {{Arable}}</li>
<li>Climate: {{Climate}}</li>
<li>Birthrate: {{Birthrate}}</li>
<li>Deathrate: {{Deathrate}}</li>
<li>Agriculture: {{Agriculture}}</li>
<li>Industry: {{Industry}}</li>
<li>Service: {{Service}}</li>
</ul>
</div>
</div>
</div>
</div>
Javascript:
Template7.registerHelper('json_stringify', function (context) {
return JSON.stringify(context);
});
var myApp = new Framework7({
animateNavBackIcon: true,
// Enable templates auto precompilation
precompileTemplates: true,
// Enabled pages rendering using Template7
template7Pages: true
// Specify Template7 data for pages
});
// Export selectors engine
var $$ = Dom7;
function getCountries() {
$$.getJSON('../countries.json', function (json) {
myApp.template7Data.countrylist = json ;
});
};
getCountries();
// Add main View
var mainView = myApp.addView('.view-main', {
// Enable dynamic Navbar
dynamicNavbar: true,
});

nested ng-repeat with json and rest api call back

I am trying to make a UI using list of product in a json(products.json) file on local and their availability in number from wp rest api call back in html(ionic) I have this:
Controller:
.controller('ShopCtrl', function($scope, $ionicActionSheet, BackendService, CartService, $http, $sce ) {
$scope.siteCategories = [];
$scope.cart = CartService.loadCart();
$scope.doRefresh = function(){
BackendService.getProducts()
.success(function(newItems) {
$scope.products = newItems;
console.log($scope.products);
})
.finally(function() {
// Stop the ion-refresher from spinning (not needed in this view)
$scope.$broadcast('scroll.refreshComplete');
});
};
$http.get("http://example.com/wp-json/wp/v2/categories/").then(
function(returnedData){
$scope.siteCategories = returnedData.data;
console.log($scope.siteCategories);
}, function(err){
console.log(err);
});
Template view:
<div ng-repeat = "product in products">
<div class="item item-image" style="position:relative;">
<img ng-src="{{product.image}}">
<div ng-repeat = "siteCategory in siteCategories">-->
<button class="button button-positive product-price" ng-click="addProduct(product)">
<p class="white-color product-price-price">post <b>{{siteCategory[$index].count}}</b></p>
</button>
</div>
</div>
<div class="item ui-gradient-deepblue">
<h2 class="title white-color sans-pro-light">{{product.title}} </h2>
</div>
<div class="item item-body">
{{product.description}}
</div>
</div>
so how can I achieve that? I tried to use nested ng-repeat but it didn't work out.

Compile error for Angular JS with js/ajax.js and index.html

When I compile my code there is an error with angular.
The code is written from a book, and it works when I load the page using the code at the end of the question.
There seems to be two issues from what I have read. Where do I put the $scope and $compile code?
Mostly, the question is how do I load a document ready trigger with a button for angular JS?
Or should I always load the angular js and hide the code?
<div id="myTabs">
<div class="menu">
<ul class= "tabs">
<li >LIST</li>
<li >GRID</li>
<li >GRID</li>
</ul>
</div>
<div class="container" style="margin-top:100px">
<div id="a">
</div>
<div id="b">
<ul class="gallery-items" id="grid">
</ul>
</div>
<div id="c" >
<div ng-controller="myController">
<div ng-repeat="item in items">
<img ng-src="{{item.img}}" />
{{item.description}}<br>
Rating: {{item.rating}} stars<br>
<span ng-repeat="idx in stars"
ng-class=
"{true: 'star', false: 'empty'}[idx <= item.rating]"
ng-click="adjustRating(item, idx)">
</span>
<hr>
</div>
</div>
</div>
</div>
ajax.js has a function that calls the #c tab to load
$(document).ready(function(){
$('#listC').click(function(){
angular.module('myApp', [])
.controller('myController', ['$scope', function($scope) {
$scope.stars = [1,2,3,4,5];
$scope.items = [100];
$.ajax({
type:'post',
url:'changeView.php',
data:{action: 'getGrid'},
success:function(data){
var data = JSON.parse(data);
for (i=0;i<data.length;i++) {
var imageLI = makeImage(data[i]['imageID'], data[i]['name'], data[i]['desc']);
$scope.items[i] = imageLI;
}
}
});
console.log($scope.items);
$scope.adjustRating = function(item, value){
item.rating = value;
};
}]);
});
$('#listC').trigger('click');
function makeImage(ID, name, description){
var image = {
description: description,
img: '../uploads/'+name,
rating: 4
}
return image;

angularJS Custom directive functionality works using ng-click but not using ng-mouseOver

Requirement goes like this :- I have left navigation panel which has to be in sync with the items added in the main active view by the user and has to display in tree structure. Basic idea is to provide context aware sub-view that change based on active view.
Custom directive used to display tree structure: https://github.com/nickperkinslondon/angular-bootstrap-nav-tree/blob/master/src/abn_tree_directive.js
my HTML code: (using ng-click)
<div class="add-data-request-panel" style="min-height:1071px;"
ng-click="expandPanel()">
<ul>
<li class="icon-drd icon-drd-diactive" ng-if="panelCollapse" ></li>
<li class="icon-pie-chart icon-pie-active" ng-if="panelCollapse"></li>
<li class="icon-publish-req" ng-if="panelCollapse"></li>
<li class="icon-view-changes" ng-if="panelCollapse"></li>
</ul>
</div>
<div class="data-slider-panel" style="min-height:1071px;display" ng-if="panelExpand">
<div class="data-slider-row mtop" ng-click="collapsePanel()">
<div class="slider-row-left">
<span class="first-char" >S</span>
<span class="second-char">ection</span>
</div>
<div class="slider-row-right">
<div class="icon-drd icon-drd-diactive">
</div>
</div>
</div>
<div class="data-slider-row">
<div class="slider-row-left">
Section2
<div class="sub-slider-row-left">
<abn-tree tree-data="mainArrayObj"></abn-tree> // passing data to tree directive
</div>
</div>
<div class="slider-row-right">
<div class="icon-pie-chart icon-pie-active">
</div>
</div>
</div>
<div class="data-slider-row" ng-click="collapsePanel()">
<div class="slider-row-left">
Section3
</div>
<div class="slider-row-right">
<div class="icon-publish-req">
</div>
</div>
</div>
<div class="data-slider-row" ng-click="collapsePanel()">
<div class="slider-row-left">
Section4
</div>
<div class="slider-row-right">
<div class="icon-view-changes">
</div>
</div>
</div>
</div>
JS implementation in my controller
$scope.panelExpand = false; //setting default flag
$scope.panelCollapse = true; //setting default flag
$scope.expandPanel = function() {
$scope.panelExpand = true;
$scope.panelCollapse = false;
$scope.mainArrayObj = []; // array that holds the data passed in html to custom directive
initialJsonSeparator($scope.model.Data); // method used for iteration
};
$scope.collapsePanel = function() {
$scope.panelExpand = false;
$scope.panelCollapse = true;
};
my HTML code: (using ng-mouseover which is not working and displaying the data passed to navigation bar)
<div class="add-data-request-panel" style="min-height:1071px;" ng-mouseover="hoverIn()"
ng-mouseleave="hoverOut()">
<ul>
<li class="icon-drd icon-drd-diactive"></li>
<li class="icon-pie-chart icon-pie-active"></li>
<li class="icon-publish-req"></li>
<li class="icon-view-changes"></li>
</ul>
</div>
<div class="data-slider-panel" style="min-height:1071px;display"
ng-mouseover="hoverIn()" ng-mouseleave="hoverOut()" ng-show="hoverEdit">
<div class="data-slider-row mtop">
<div class="slider-row-left">
<span class="first-char">S</span>
<span class="second-char">ection1</span>
</div>
<div class="slider-row-right">
<div class="icon-drd icon-drd-diactive">
</div>
</div>
</div>
<div class="data-slider-row">
<div class="slider-row-left">
Section2
<div class="sub-slider-row-left">
<abn-tree tree-data="mainArrayObj"></abn-tree> // array that holds the data passed in html to custom directive
</div>
</div>
<div class="slider-row-right">
<div class="icon-pie-chart icon-pie-active">
</div>
</div>
</div>
<div class="data-slider-row">
<div class="slider-row-left">
Section3
</div>
<div class="slider-row-right">
<div class="icon-publish-req">
</div>
</div>
</div>
<div class="data-slider-row">
<div class="slider-row-left">
Section4
</div>
<div class="slider-row-right">
<div class="icon-view-changes">
</div>
</div>
</div>
</div>
js Implementation for the ng-mouseOver: (while debugging all the iteration and methods executed as expected)
$scope.hoverIn = function() {
this.hoverEdit = true;
$scope.mainArrayObj = []; // array that holds the data passed in html to custom directive
initialJsonSeparator($scope.model.Data); //method used to iterate the data
};
$scope.hoverOut = function() {
this.hoverEdit = false;
};
Any solution to this issue would be of gr8 help. If there is any other better approach other than the ng-mouseOver and ng-mouseLeave to implement hover, please do let me know.

Simple previous\next slider using angular

I have a web page which displays a list of items, the number of items can get quite big so I would like to display only 3 at a time and have next\previous buttons which let the user navigate between items.
I'm very new to Angular but I managed to retrieve all the items and display them on the UI but have no idea where to start to only display three and wire up the next and previous buttons to enable navigation.
Here's my code:
JS:
var app = angular.module('myApp', []);
app.controller('servicesController', function ($scope, $http) {
$http.get(url + "api/MapServiceAPI/GetServers")
.success(function (response) {
$scope.servers = response.Result;
});
});
HTML:
<div class="row top-space" ng-app="myApp" ng-controller="servicesController">
<div class="pull-left">
<img src="~/Content/Images/Service/PREVIOUS.png" />
<h4>PREVIOUS</h4>
</div>
<div class="pull-right">
<img src="~/Content/Images/Service/NEXT.png" />
<h4>NEXT</h4>
</div>
<ul class="col-md-3 text-center" ng-repeat="s in servers" ng-click="serviceClick(s.ServiceId)">
<li>
<div class="container">
<h4>{{ s.ServerName }}</h4>
</div>
<div class="container">
<img src="~/Content/Images/Server/SERVER.png" />
</div>
<div class="container">
<h5>{{ s.ServerDescription }}</h5>
</div>
</li>
</ul>
</div>
you can achieve using filters limitTo property
> <li ng-repeat="datalist in datalists | pagination: curPage * pageSize
> | limitTo: pageSize">
refere this jsfiddle which help you to understand better.
http://jsfiddle.net/dulcedilip/x7tg15v9/

Categories