Show first JSON data Object without selecting any link using Angular JS - javascript

I'm trying to build a webpage to show JSON data based on the link we select and i had done it and its working fine. My issue is I need to show first JSON data object before selecting any link (initially).
Plunker Link - http://embed.plnkr.co/SPbvgPhfdeCqZG0yzzeZ/
My HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Testing</title>
<link href="css/style.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular-route.js"></script>
</head>
<body ng-app="richPortfolio">
<div class="container" ng-controller="adsCtrl">
<nav>
<ul class="accordion" onclick="myFunction(event)">
<li ng-repeat="ad in ads">
<a class="ad" href="" id="ad{{ ad.id }}" ng-click="select(ad)">{{ ad.title }}</a>
</li>
</ul>
</nav>
<div class="showCase_container">
<div id="ad{{ selectedItem.id }}Case" class="adActive">
<div class="description">
<h3 class="ad_name">{{ selectedItem.title }}</h3>
<p>{{selectedItem.content}}</p>
<hr>
<h3>Description</h3>
<p>{{ selectedItem.desc }}</p>
<hr>
<h3>Dimension</h3>
<p>{{ selectedItem.dim }}</p>
</div>
</div>
</div>
</div>
<script src="rich.js"></script>
</body>
</html>
My JSON:
[
{
"id": "1",
"title": "cube",
"content": "cube 1 cube",
"desc":"orem ipsum dolor sit amet, consectetur adipiscing elit",
"dim":"300x250"
},
{
"id": "2",
"title": "Gallery",
"content": "Gallery 2 Gallery",
"desc":"orem ipsum dolor sit amet, consectetur adipiscing elit",
"dim":"300x250, 300x600, 728x90, 970x250"
}
]
My JS:
// Modules
var rich = angular.module('richPortfolio', ['ngRoute']);
rich.config(function($routeProvider){
$routeProvider
.when('/', {
controller: 'adsCtrl',
templateUrl: 'pages/home.html'
})
.otherwise({ redirectTo: '/' });
});
// controllers
rich.controller('adsCtrl', ['$scope', 'ads', function($scope, ads , element){
ads.then(function(data){
$scope.ads = data;
});
// devices
$scope.tab = 1;
$scope.setTab = function(newTab){
$scope.tab = newTab;
};
$scope.isSet = function(tabNum){
return $scope.tab === tabNum;
};
// nav redirection
$scope.select = function(item) {
$scope.selectedItem = item;
};
}]);
//services
rich.factory('ads', ['$http', function($http){
// after v1.6 need to use .then function to get it worked
return $http.get('ads.json')
.then(function(response){
//alert('success');
return data = response.data;
},function(error){
//alert('error');
});
}]);
function myFunction(e) {
var elems = document.querySelector(".accordion .active");
if(elems !==null){
elems.classList.remove("active");
}
e.target.className = "active";
}
Plunker Link - http://embed.plnkr.co/SPbvgPhfdeCqZG0yzzeZ/
Now after selecting the respective link it shows the corresponding data. Need to show first JSON data object before selecting any link.
Any help would be appreciated.

When you click and a element you call a function named select(ad) which set some info to the $scope.selectedItem property and you're displaying that variable info. So, in order to get the some data before click something you should set a default value the $scope.selectedItem property. Check this code:
rich.controller('adsCtrl', ['$scope', 'ads', function($scope, ads , element){
ads.then(function(data){
$scope.ads = data;
$scope.selectedItem = data[0]; //Set default element
});

Related

JsonPlaceHolder multiple api call using AngularJS

I am very new to angular js and I have been hanging around with api. The following code shows the name of the user and the name of the user when it is clicked. What I'm trying to do is I want the user to get the todos title when the button is clicked. https://jsonplaceholder.typicode.com/todos. how can I do that ? I know it's a bit confusing, but I'm waiting for you guys.
jsonplaceholder.html
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js">
</script>
<script src="script.js"></script>
<head>
<title>JsonPlaceHolder</title>
</head>
<body>
<div ng-app="myApp" ng-controller="customersCtrl">
<ul>
<li ng-repeat="x in myData">
{{ x.name }}
<button ng-click="getResult($index)">Click</button>
</li>
</ul>
<h2>Results</h2>
<p><code>Title : </code> {{indexResult.name}}</p>
</div>
</body>
</html>
script.js
var app = angular.module('myApp', []);
var root = 'http://jsonplaceholder.typicode.com/users';
app.controller('customersCtrl', function($scope, $http) {
$http.get(root).then(function (response) {
$scope.myData = response.data;
});
$scope.getResult = function($index) {
$scope.indexResult = $scope.myData[$index];
};
});
I write your code like this:
var app = angular.module('myApp', []);
var root = 'http://jsonplaceholder.typicode.com/users';
var todos= 'https://jsonplaceholder.typicode.com/todos'
app.controller('customersCtrl', function($scope, $http) {
$http.get(root).then(function (response) {
$scope.myData = response.data;
});
$scope.getResult = function(item) {
$scope.titleList = [];
$http.get(todos).then(function (response) {
$scope.todosList = response.data; }).then(()=> {
$scope.todosList.map(it=> {
if (it.userId === item.id){
$scope.titleList.push({title: it.title , id: it.userId});
}
});
});
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!DOCTYPE html>
<html>
<script src="app.js"></script>
<head>
<title>JsonPlaceHolder</title>
</head>
<body>
<div ng-app="myApp" ng-controller="customersCtrl">
<ul>
<li ng-repeat="x in myData">
{{ x.name }}
<button ng-click="getResult(x)">Click</button>
</li>
</ul>
<h2>Results</h2>
<ul>
<li ng-repeat="item in titleList">
{{ item.title }}
</li>
</ul>
</div>
</body>
</html>

custom directives not working with angularjs routeprovider

I am very new to angularjs and learning as of now. I am currently learning angularjs route provider. I had built a couple of pages which independently worked fine. I am trying to now implement route provider. In my welcome.html page i am using an third party slide out panel http://dpiccone.github.io/ng-pageslide/examples/
I used it in a single page it worked fine. I am now trying to implement route provider as below
My index.html
<html ng-app="ui.bootstrap.demo">
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular-animate.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular-route.js"></script>
<script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-1.3.3.js"></script>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://rawgit.com/esvit/ng-table/master/dist/ng-table.min.css">
<script src="https://rawgit.com/esvit/ng-table/master/dist/ng-table.min.js"></script>
<script src="resources/js/main.js"></script>
<script src="resources/js/CarouselController.js"></script>
<script src="resources/js/dashboardrouter.js"></script>
<script src="resources/js/TypeAheadController.js"></script>
<script src="resources/js/angular-pageslide-directive.js"></script>
</head>
<body>
<h2>AngularJS Sample Application</h2>
<div ng-view></div>
</body>
</html>
my app file
angular.module('ui.bootstrap.demo', ['ngAnimate', 'ui.bootstrap', 'ngTable', 'ngRoute']);
My routeprovider
angular.module('ui.bootstrap.demo').config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/welcome', {
templateUrl: 'welcome.html',
controller: 'CarouselDemoCtrl'
}).
when('/queryBoard/:gridName', {
templateUrl: 'query/queryboard.html',
controller: 'documentNameTypeAheadController',
}).
otherwise({
redirectTo: '/welcome'
});
}]);
my welcome.html file
<html ng-app="ui.bootstrap.demo">
<body>
<style type="text/css">
body {
background: url(/resources/images/nyc.jpg) center top no-repeat;
}
.ng-pageslide {
background: #ac2925;
}
</style>
<div>
<h1 class="text-center text-primary centered">Welcome to ananta-gs dashboard</h1>
<div>
<uib-carousel active="active" interval="myInterval" no-wrap="noWrapSlides" style="height: 305px; width: 450px; margin:auto">
<uib-slide ng-repeat="slide in slides track by slide.id" index="slide.id">
<img ng-src="/resources/images/cloud-home.jpg" style="height:305px; margin:auto;">
<div class="carousel-caption">
<a ng-click='sendEnvName(slide.text)'>
<h3 class="carousel-caption text-primary center-block">
{{slide.text}}</h3>
</a>
</div>
</uib-slide>
</uib-carousel>
There are exceptions during app initialization, click here to see details
</div>
<div>
<pageslide ps-open="checked" ps-side="left" ps-squeeze="true">
<div style="padding:20px" id="demo-right">
<h2>Exceptions : </h2>
<p style="word-wrap: break-word">{{exceptions}}</p>
<a ng-click="toggle()" class="button">Close</a>
</div>
</pageslide>
</div>
</div>
</body>
</html>
All the bootstrap components are working fine, i.e. carousel is working fine and i am sure that my CarouselDemoCntrl is also invoked, as its fetching the data.
But the components like <pageslide> are not working which are defined in the angular-pageslide-directive.js
Similarly i have a page queryboard.html is used ngTableParams, angular is not able to resolve that also.
Expected behavior for pageslide is that, when i click on "There are exceptions during app initialization, click here to see details" a slide out panel should appear which contains the list of exceptions, instead what i am seeing here is that instead of slideout panel, it is printed in plain text in html page.
Below is the code for CarouselDemoCtrl
angular.module('ui.bootstrap.demo').controller('CarouselDemoCtrl', function ($scope, $http, $uibModal, $location) {
$scope.myInterval = 5000;
$scope.noWrapSlides = false;
$scope.active = 0;
$scope.errorShow = false;
var slides = $scope.slides = [];
var currIndex = 0;
$scope.addSlide = function (envName) {
slides.push({
text: envName,
id: currIndex++
});
};
$http.get("http://localhost:8080/getEnvList")
.success(function (data) {
var envs = data.spaceLookUpDetailsList;
for (var i in envs) {
$scope.addSlide(envs[i].envName);
}
if(data.exceptions) {
$scope.errorShow = true;
$scope.exceptions = data.exceptions;
}
})
.error(function (errordata) {
$uibModal.open({
templateUrl: 'error/ErrorModal.html',
controller: 'ErrModalInstanceCtrl',
resolve: {
error: function () {
console.log('error=' + errordata.errorMessage)
return errordata;
}
}
});
});
$scope.toggle = function () {
$scope.checked = !$scope.checked;
}
$scope.sendEnvName = function (gridName) {
alert(gridName)
$location.path("/queryBoard/"+gridName);
}
});
angular.module('ui.bootstrap.demo').controller('ErrModalInstanceCtrl', function ($scope, $uibModalInstance, error) {
$scope.errormessage = error.errorMessage;
$scope.stacktrace = error.stackTrace;
$scope.ok = function () {
$uibModalInstance.close('closed');
};
});
Can some please guide me here
Two problems here:
First, you did not inject the module for pageslide ("pageslide-directive")
You want this:
angular.module('ui.bootstrap.demo', ['pageslide-directive', 'ngAnimate', 'ui.bootstrap', 'ngTable', 'ngRoute']);
Second, you wrote welcome.html as if it were a distinct web page, instead of as a template (which is what you want). Remove the html and body tags from welcome.html, and you should be all set.

console.log for $scope in angular js

Why I'm not able to console output $scope values ? I'm trying to extract user assigned values from the pages and retrieve in controller. Eventually i would like to pass this to service so multiple controllers can access these data.
HTML
<!DOCTYPE html>
<html lang="en-us" ng-app="myApp">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
<meta charset="UTF-8">
<link rel="stylesheet" href="css/bootstrap.min.css" />
<!-- CDN lib files -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular-animate.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/1.1.0/ui-bootstrap-tpls.min.js"></script>
<!-- custom angular script -->
<script src="js/app.js"></script>
</head>
<body>
<div class="container">
<div ng-controller="mainController">
<h1>Hello world!</h1>
<label> Please enter something</label>
<input textarea ng-model="name"></input>
<h4> This is what you entered : {{ name }} </h4>
<h4 style=color:red> now filtering: {{ lower() }}</h4>
</div>
</div>
</body>
</html>
APP.JS
var myApp = angular.module('myApp', []);
myApp.controller('mainController', ['$scope', '$filter', function($scope, $filter) {
$scope.name = 'Test ';
$scope.lower = function(){
return $filter('lowercase')($scope.name);
}
$scope.name = $scope.lower();
console.log($scope.name);
console.log($scope.lower());
}]);
Console will output values upon initializing but not after user make changes.
You need to watch the scope variable:
$scope.$watch('name', function() {
console.log($scope.name);
});
More information: https://stackoverflow.com/a/15113029/5787736
Just a more "functional" version. Everyone is right, you are logging the observable, not what was observed. What you want is for console.log to be called on each change to $scope, not called once (as you have it now).
$scope.$watch("name", console.log);
You're logging only from the constructor. If you want to log each time something changes, consider a watch:
$scope.$watch("name", function() {
console.log($scope.name);
}
Why would you expect a controller to be rerendered when a scope variable changes? You can use scope watchers or input event listeners to listen for changes.
Here's an example with a watcher:
var myApp = angular.module('myApp', []);
myApp.controller('mainController', ['$scope', '$filter', function($scope, $filter) {
$scope.name = 'Test ';
$scope.lower = function(){
return $filter('lowercase')($scope.name);
}
$scope.name = $scope.lower();
console.log($scope.name);
console.log($scope.lower());
$scope.$watch('name', function() {
console.log($scope.name);
console.log($scope.lower());
});
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" class="container">
<div ng-controller="mainController">
<h1>Hello world!</h1>
<label>Please enter something</label>
<input textarea ng-model="name" />
<h4> This is what you entered : {{ name }} </h4>
<h4 style=color:red> now filtering: {{ lower() }}</h4>
</div>
</div>

Ionic: How do i load only 1 image from my json file?

I've managed to load all my images from my json file into the application but i would only like 1 image to be loaded. I'm using ng-repeat which is why it keeps repeating itself. What do i replace ng-repeat with so it only shows the first image?
Here's my code.
Html:
<div ng-click="onClick()">
<i class="ion-images"></i>
</div>
<a ng-controller="Ctrl">
<ion-scroll direction="x">
<img on-hold="onHold()" ng-repeat="image in data" ng-src="{{image.image}}" />
</ion-scroll>
</a>
js:
.controller("Ctrl", function($scope, $http, $ionicModal) {
$scope.data = [];
$http.get('')
.success(function(data) {
$scope.data = data;
window.localStorage.setItem("images", JSON.stringify(data));
})
});
If you want display only first element from your array you don't have use ng-repeater, you can access it using array index ie:
ng-src="{{data.under9s[0].image}}
Please see working demo below:
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope, $http) {
$scope.data = [];
$http.get('https://api.myjson.com/bins/4tutm')
.success(function(data) {
$scope.data = data;
window.localStorage.setItem("images", JSON.stringify(data));
})
.error(function(error) {
if (window.localStorage.getItem("images") !== undefined) {
$scope.data = JSON.parse(window.localStorage.getItem("images"));
}
});
});
<!DOCTYPE html>
<html ng-app="plunker">
<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.4.x" src="https://code.angularjs.org/1.4.3/angular.js" data-semver="1.4.3"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<p>Hello {{name}}!</p>
<ion-scroll direction="x">
<img on-hold="onHold()" ng-src="{{data.under9s[0].image}}" ng-click="showImages($index)" class="image-list-thumb" />
</ion-scroll>
</body>
</html>

Using ng-repeat across two containers

I'm creating an application that has two boxes. On the left div it will display a list of clickable links, once clicked it will display that links information on the div to the right. I've managed to get my data to hide and show when the link is clicked but only within the same div. What's the best appraoch when it comes to doing this with Angular?
<div class="row" ng-controller="faqController">
<div class="col-md-6">
<div class="col-md-12">
<div class="guide-section">
<h1>Select a Topic</h1>
<ul ng-repeat="faq in faqs">
<li>{{ faq.title }}</li>
</ul>
</div>
</div>
</div>
<div class="col-md-6">
<div class="guide-section">
<div ng-repeat="faq in faqs">
<h1>{{ faq.title }}</h1>
<p>{{ faq.info }}</p>
</div>
</div>
</div>
</div>
Angular:
var myApp = angular.module('supportApp', ['ngRoute', 'ngResource']);
myApp.controller('faqController', ['$scope', '$http', function($scope, $http) {
$scope.showData = true;
$http.get('data/faq.json').
success(function(data, status, headers, config) {
$scope.faqs = data;
//console.log(data);
}).
error(function(data, status, headers, config) {
//Complete error fallback
});
}]);
you should add to your second div ng-show='showdata' - another option would be to show if $scope.showFaq is populated, which would eliminate dealing with another variable
Also, you ng-repeat should be in your li not ul - ng-repeat should be on the element you want to repeat (unlike most for loops in other languages)
Once you populate the $scope.faqs, the list will show with the links.
Once you click the selected faq, it is used to populate the $scope.showFaq and $scope.showData is set to true...
// main.js
var app = angular.module('myApp', []);
app.controller('MyCtrl', function($scope) {
$scope.showData = false;
$scope.showHide = function(faq) {
$scope.showData = true;
$scope.showFaq = faq;
};
$scope.faqs = [
{'title': 'title 1', 'info': 'info 1'},
{'title': 'title 2', 'info': 'info 2'}
];
});
<!DOCTYPE html>
<html ng-app="myApp">
<head lang="en">
<meta charset="utf-8" />
<title>Custom Plunker</title>
<link rel="stylesheet" type="text/css" href="style.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.min.js"></script>
<script type="text/javascript" src="main.js"></script>
</head>
<body ng-controller="MyCtrl">
<div class="col-md-6">
<div class="col-md-12">
<div class="guide-section">
<h1>Select a Topic</h1>
<ul>
<li ng-repeat="faq in faqs"><a ng-click="showHide(faq)">{{ faq.title }}</a></li>
</ul>
</div>
</div>
</div>
<div class="col-md-6">
<div class="guide-section" ng-show="showData">
<h1>{{ showFaq.title }}</h1>
<p>{{ showFaq.info }}</p>
</div>
</div>
</body>
</html>

Categories

Resources