JsonPlaceHolder multiple api call using AngularJS - javascript

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>

Related

ng click function not working in angularJS controller

Here is my code, Actually when I click on function but not showing alert and not getting error in console. So please tell me how to do.
HTML Code
<li class="has-megamenu" ng-click="homepage()" ><a ><span >Home</span></a>
</li>
app.js
app.controller('myController', function($scope){
$scope.homepage = function(){
alert('hi');
}});
There can be two reasons
1- Not using ng-app directive in the root element of your application.
2- You have not defined ng-controller properly.
Please follow following working code.
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.js"></script>
<script>
var app = angular.module('app', []);
app.controller('myController', function($scope) {
$scope.homepage = function() {
alert('hi');
}
});
</script>
</head>
<body ng-app="app">
<div ng-controller="myController">
<ul>
<li class="has-megamenu" ng-click="homepage()"><a><span >Home</span></a>
</li>
</ul>
</div>
</body>
</html>
First You have to add ng-app = "app"
Second You have to add ng-controller = "myController"
Final
Please check the updated code:
var app = angular.module("app", []);
app.controller('myController', function($scope){
$scope.homepage = function(){
alert('hi');
}});
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</head>
<body ng-app = "app">
<div ng-controller = "myController">
<li class="has-megamenu" ng-click="homepage()" ><a ><span >Home</span></a>
</li>
<div>
</body>
</html>

Angular not working

I'm new to angular. Just trying to replicate this jsfiddle to play with nodes, but the angular is not working. First, the jsfiddle is confusing my as the application names are not he same. Secondly, it looks like and old version. What am I doing wrong when setting up the application. Is something missing with the templates, or the order of scripts out of place?
<html>
<head>
<script src="https://code.angularjs.org/angular-1.0.0rc8.js"></script>
<style>
ul {
list-style: circle;
}
li {
margin-left: 20px;
}
</style>
</head>
<body>
<script type="text/ng-template" id="tree_item_renderer.html">
{{data.name}}
<button ng-click="add(data)">Add node</button>
<button ng-click="delete(data)" ng-show="data.nodes.length > 0">Delete nodes</button>
<ul>
<li ng-repeat="data in data.nodes" ng-include="'tree_item_renderer.html'"></li>
</ul>
</script>
<ul ng-app="Application" ng-controller="TreeController">
<li ng-repeat="data in tree" ng-include="'tree_item_renderer.html'"></li>
</ul>
<script>
angular.module("myApp", []).
controller("TreeController", ['$scope', function($scope) {
$scope.delete = function(data) {
data.nodes = [];
};
$scope.add = function(data) {
var post = data.nodes.length + 1;
var newName = data.name + '-' + post;
data.nodes.push({name: newName,nodes: []});
};
$scope.tree = [{name: "Simon", nodes: []}];
}]);
</script>
</body>
</html>
ng-appshould target a module. Try ng-app="myApp".

AngularJS Display 1 Post in New Page

I want to display only Test Post 1 in next html page titleDetails.html when user clicks Test Post 1 in index.html
1) titleDetails() in index.html:
<a ng-click="titleDetails(post)">{{ post.title }} </a>
2) controller variables and titleDetails() method:
function BlogController($scope, $http, $rootScope, $location) {
$scope.createPost = createPost;
$scope.deletePost = deletePost;
$scope.editPost = editPost;
$scope.updatePost = updatePost;
$scope.titleDetails = titleDetails;
$scope.postDetail = null;
function titleDetails(post)
{
$scope.postDetail = post;
$location.path('#/titleDetails');
}
3) body in titleDetails.html:
<body>
<div class="container" ng-controller="BlogController">
<h1>Blog</h1>
<div>
<h2>
<a>{{ postDetail.title }} </a>
</h2>
<em>{{postDetail.posted}}</em>
<p>{{postDetail.body}}</p>
</div>
</div>
</body>
FULL CODE:
app.js
(function () {
angular
.module("BlogApp", [])
.controller("BlogController", BlogController);
function BlogController($scope, $http, $rootScope, $location) {
$scope.createPost = createPost;
$scope.deletePost = deletePost;
$scope.editPost = editPost;
$scope.updatePost = updatePost;
$scope.titleDetails = titleDetails;
$scope.postDetail = null;
function init() {
getAllPosts();
}
init();
function titleDetails(post)
{
$scope.postDetail = post;
$location.path('#/titleDetails');
}
function updatePost(post){
console.log(post);
$http
.put("/api/blogpost/"+post._id, post)
.success(getAllPosts);
}
function editPost(postId){
$http
.get("/api/blogpost/"+postId)
.success(function(post){
$scope.post = post;
});
}
function deletePost(postId){
$http
.delete("/api/blogpost/"+postId)
.success(getAllPosts);
}
function getAllPosts(){
$http
.get("/api/blogpost")
.success(function(posts) {
$scope.posts = posts;
});
}
function createPost(post) {
console.log(post);
$http
.post("/api/blogpost",post)
.success(getAllPosts);
}
}
})();
index.html
<!DOCTYPE html>
<html lang="en" ng-app="BlogApp">
<head>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
<script src="app.js"></script>
<title>Title</title>
</head>
<body>
<div class="container" ng-controller="BlogController">
<h1>Blog</h1>
<input ng-model="post.title" class="form-control" placeholder="title"/>
<textarea ng-model="post.body" class="form-control" placeholder="body"></textarea>
<button ng-click="createPost(post)" class="btn btn-primary btn-block">Post</button>
<button ng-click="updatePost(post)" class="btn btn-success btn-block">Update</button>
<div ng-repeat="post in posts">
<h2>
<a ng-click="titleDetails(post)">{{ post.title }} </a>
<a ng-click="editPost(post._id)" class="pull-right"><span class="glyphicon glyphicon-pencil"></span></a>
<a ng-click="deletePost(post._id)" class="pull-right"><span class = "glyphicon glyphicon-remove"></span></a>
</h2>
<em>{{post.posted}}</em>
<p>{{post.body}}</p>
</div>
</div>
</body>
</html>
titleDetails.html:
<!DOCTYPE html>
<html lang="en" ng-app="BlogApp">
<head>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
<script src="app.js"></script>
<title>Title</title>
</head>
<body>
<div class="container" ng-controller="BlogController">
<h1>Blog</h1>
<div>
<h2>
<a>{{ postDetail.title }} </a>
</h2>
<em>{{postDetail.posted}}</em>
<p>{{postDetail.body}}</p>
</div>
</div>
</body>
</html>
Hope this following steps work for you
Pass post object to titleDetail() function.
In index.html
<a ng-click="titleDetails(post)">{{ post.title }} </a>
In function assign post to $rootScope variable
$scope.titleDetails = function(post) {
$rootScope.postDetail = post;
}
Now your titleDetail.html page controller:
$scope.post = $rootScope.postDetail;
a new scope variable in BlogController
$scope.postDetail = null;
and method titleDetails() be like
$scope.titleDetails = function(post) {
$scope.postDetail = post;
}
and also make change in index.html
<a ng-click="titleDetails(post)">{{ post.title }} </a>

how to show response data in angularjs

i have following code but my page does not show data...;( i don't now why please help me, i am new in angularjs. I AM calling web API its working fine console log show json record, but in my page record does now show... why
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="Scripts/angular.min.js"></script>
<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$http.get("http://localhost:9000/employees").then(function (response) {
$scope.myData = response.data;
});
});
</script>
</head>
<body>
<div ng-app="myApp" ng-controller="customersCtrl">
<br>
<p>Today's welcome message is:</p>
<!--<h1>{{myWelcome}}</h1>-->
<ul>
<li ng-repeat="x in myData">
<li ng-repeat="x in myData">
{{ x.ProductName }} ',' {{ x.ProductDescription }}
</li>
<!--{{ x.ProductName + ', ' + x.ProductDescription }}-->
</li>
</ul>
</div>
</body>
</html>
result = [{"ID":1,"ProductName":"xcxc","ProductDescription":"xcxc","UnitPrice":2323,"QtyAvailable":23}]
its show below error in chrome console log
XMLHttpRequest cannot load http://localhost:9000/employees. No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'null' is therefore not allowed access.
<li ng-repeat="x in myData">
{{ x.FirstName }} ',' {{ x.LastName }}
</li>
All the things are fine in your code, might angular not loaded or http not responded correct:
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$scope.myData = [{
FirstName: "firts1",
LastName: "last1"
}, {
FirstName: "firts2",
LastName: "last2"
}, ];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.20/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="customersCtrl">
<br />
<!--// <p>Today's welcome message is:</p>-->
<!--<h1>{{myWelcome}}</h1>-->
<ul>
<li ng-repeat="x in myData">
{{ x.FirstName + ', ' + x.LastName }}
</li>
</ul>
</div>
</body>
</html>
<li ng-repeat="x in myData">
{{x.FirstName}}, {{x.LastName}}
</li>
We have to use JSONP to prevent the cross origin policy.
var url = "http://localhost:9000/employees?callback=JSON_CALLBACK";
$http.jsonp(url)
.success(function(data){
console.log(data);
});
or
If you want to disable policy then follow below steps
For Windows... create a Chrome shortcut on your desktop.
Right-clic > properties > Shortcut
Edit "target" path :
"C:\Program Files\Google\Chrome\Application\chrome.exe" --args --disable-web-security
Then try with your existing code

Issue with Angular don't see my data

I want that in the init to bind the model of my controller the init is called but I don't see any data what is wrong ?
Index.html
<!DOCTYPE html>
<html ng-app="I-Sign">
<head>
<meta http-equiv='X-UA-Compatible' content='IE=edge' />
<meta name="viewport" content="width=device-width" />
<title>Sign Language Application</title>
<link rel="stylesheet" href="scripts/jquery.mobile-1.4.5.css" />
<script type="text/javascript" charset="utf-8" src="scripts/jquery.js"></script>
<script type="text/javascript" charset="utf-8" src="scripts/jquery.mobile-1.4.5.js"></script>
<script type="text/javascript" charset="utf-8" src="scripts/angular.js"></script>
<script type="text/javascript" charset="utf-8" src="scripts/lodash.js"></script>
<script src="mainController.js"></script>
</head>
<body>
<div ng-controller="MainCtrl as ctrl" ng-init="init()">
<div id="categories">
     <ul data-role="listview" data-inset="true">
         <li ng-repeat="category in ctrl.data.categories"><a ng- click="ctrl.showWords(category)" href="#">
                 <img src="images/Can_I.png">
                 <h1>{{category.name}}</h1>
        </a>   
        </li>
</ul>
</div>
<div id="words">
    <ul data-role="listview" data-inset="true">
            
        <li ng-repeat="word in ctrl.currentWords"><a ng-click="ctrl.showMovie()" href="#">
                 <img src="images/Can_I.png">
                 <h1>{{word.name}}</h1>
        </a>                 
        </li>
</ul>
<div>
<input id="upBtn" class="ui-block-a" type="button" value="UP" ng-hide ng-click="ctrl.showCategories()">
</div>
</div>
mainController.js
var myApp = angular.module('I-Sign',[]);
myApp.controller('MainCtrl', ['$scope', function($scope) {
var self = $scope;
$scope.init = function () {
var that = this;
that.getData();
self.currentWords = [];
}
$scope.$watchCollection(function () {
//var that = this;
return self.data;
}, function () {
console.log("Changed");
});
$scope.getData = function () {
var that = this;
$.getJSON('data/database.json', function (data) {
that.data = data;
});
}
$scope.showCategories = function () {
var that = this;
$("#words").addClass("ng-hide");
$("#categories").removeClass("ng-hide");
$("#upBtn").assClass("ng-hide");
}
$scope.showWords = function (category) {
var that = this;
that.currentWords = [];
$("#categories").addClass("ng-hide");
$("#words").removeClass("ng-hide");
$("#upBtn").removeClass("ng-hide");
that.data.words.forEach(function (word) {
if (word.categoryId === category.id) {
that.currentWords.push(word);
}
});
}
}]);
Since you used jquery to get your data, you need to run a .$apply() as the code happened outside of angulars knowledge
$.getJSON('data/database.json', function (data) {
that.data = data;
$scope.$apply();
});
Alternatively you should not be using jquery at all and instead inject $http in (like you did with $scope) and use that:
$http.get('data/database.json')
.success(function(data){
that.data = data;
});
Additionally change the following:
$scope.showCategories = function () {
$scope.showCategories = true;
}
$scope.showWords = function (category) {
that.currentWords = [];
$scope.showCategories = false;
that.data.words.forEach(function (word) {
if (word.categoryId === category.id) {
that.currentWords.push(word);
}
});
}
and your html to:
<div id="categories" ng-show="showCategories">
<ul data-role="listview" data-inset="true">
<li ng-repeat="category in ctrl.data.categories">
<a ng-click="ctrl.showWords(category)" href="#">
<img src="images/Can_I.png">
<h1>{{category.name}}</h1>
</a>
</li>
</ul>
</div>
<div id="words" ng-show="!showCategories">
<ul data-role="listview" data-inset="true">
<li ng-repeat="word in ctrl.currentWords">
<a ng-click="ctrl.showMovie()" href="#">
<img src="images/Can_I.png">
<h1>{{word.name}}</h1>
</a>
</li>
</ul>
</div>
<div>
<input id="upBtn" class="ui-block-a" type="button" value="UP" ng-show="!showCategories" ng-click="ctrl.showCategories()">
</div>

Categories

Resources