How to get data from JSON using Angularjs? - angularjs

var app = angular.module("app", []);
app.controller('emp', ['$scope', 'empService', function($scope, empService){
$scope.doSearch = function(){
empService.findEmployeeById($scope.searchempno, function(r){
$scope.empno = r.empno;
$scope.ename = r.ename;
$scope.salary = r.salary;
$scope.dptno = r.dptno;
});
};
}]);
app.service('empService', ['$http', '$log', function($http, $log){
this.findEmployeeById = function(empno, cb){
$http({
url: 'employees.json' + empno,
method: 'GET'
}).then(function(resp){
cb(resp.data);
});
};
}]);
<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
<script type="text/javascript" src="app.js"></script>
</head>
<body ng-app="app">
<div ng-controller="emp">
<form class="form-inline">
<div class="form-group">
<label>Enter Employee Number:</label>
<input type="text" class="form-control" ng-model="searchEmpno"/>
</div>
<button class="btn btn-primary" ng-click="doSearch()">Search</button>
</form>
<hr>
<div class="row">
<div class="col-sm-2">Employee No</div>
<div class="col-sm-2">{{empno}}</div>
</div>
<div class="row">
<div class="col-sm-2">Employee Name</div>
<div class="col-sm-2">{{ename}}</div>
</div>
<div class="row">
<div class="col-sm-2">Salary</div>
<div class="col-sm-2">{{salary}}</div>
</div>
<div class="row">
<div class="col-sm-2">Deptno</div>
<div class="col-sm-2">{{dptno}}</div>
</div>
</div>
</body>
</html>
If I gave the number in input field like 1001 and click the search button. It will not show the details. I have checked the console, there is no error. My JSON file has been placed the same location of the HTML file.
Thanks,
SamBhishma

I have created an updated plunker here. First issue was what I mentioned in the comment. In your view, you are writing <input type="text" class="form-control" ng-model="searchEmpno"/>and in your controller, you're trying to access this variable as searchempno
Second issue is in your http request. You cannot pick and choose the data from json file based on the id. You have to get the entire JSON file, parse it and filter out the value if it matches your searchEmpno model value. I fixed it in the plunker.
Third issue, you are attaching plain values to your scope like $scope.empno , $scope.ename. Instead, you need to put such values into an object, so in your controller, put the matched employee object in the scope and in your view, reference it as {{obj.ename}} and so on.
Another thing, no need to return callbacks inside then. The clean way of handling successful, failed http calls is:
$http.get('url').then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
Read more about them here.
Take a look at the updated plunker to see if it matches your needs.

Problem is your model variable is wrong inside the view, try this
<input type="text" class="form-control" ng-model="searchEmpno"/>
DEMO

Related

unsure of how to use filters in angularJS

Having issues getting a simple filter to work for an album selection app i'm building for experience using jsonplaceholderdata. I tried to set ng-model to an expression and filtering by that expression but nothing changes when i enter text into my input bar. Unsure as to what I'm missing.
<!DOCTYPE html>
<html>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<head>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script type="text/javascript" src="album.js"></script>
<link rel="stylesheet" href="bootstrap/css/bootstrap.min.css">
<link rel="stylesheet" href="album.css">
</head>
<body>
<div class="bar">
<input type="text" class="search" ng-model="q" placeholder="Enter your search terms" />
<button ng-click="search(q)">Search</button>
</div>
<div ng-app="myApp" ng-controller="AlbumCtrl">
<div ng-click="showme = !showme" ng-init="count=0" ng-repeat="album in albumData|filter:q" id="thumbWrapper">
<h1>{{album.id}}</h1>
<p>{{album.title}}</p>
<div id="thumbList"ng-show="showme"class="albumContent">
<ul ng-controller="PhotoCtrl" id="thumbList">
<li ng-repeat="photo in photoData" ng-if="album.userId == photo.albumId">
<img ng-src={{photo.url}}>
</li>
</ul>
</div>
</div>
</div>
This is my angular js code:
var app = angular.module('myApp', []);
app.controller('AlbumCtrl', function ($scope, $http) {
$http.get("http://jsonplaceholder.typicode.com/albums").then(function(response) {
$scope.albumData = response.data;
console.log($scope.albumData);
});
});
app.controller('PhotoCtrl', function($scope, $http) {
$http.get("http://jsonplaceholder.typicode.com/photos").then(function(response) {
$scope.photoData = response.data;
// console.log($scope.photoData);
});
});
Any help is much appreciated.
You don't need to use a controller function. Because your q is already on the $scope, it will work as soon as you start typing in the input box.
Your controller is outside of the scope of the 'q' scope variable though.

ng-controller: basic usage of controller of angularjs fail to work

I just start working on Angularjs, and when I came to ng-controller, there is one confusing point as following:
The HTML codes:
<html lang="en" ng-app="App" ng-controller="AppCtrl">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="css/bootstrap.min.css">
<title></title>
<script type="text/javascript" src="js/angular.min.js"></script>
<script type="text/javascript" src="js/controller.js"></script>
</head>
<body>
<div class="container">
<div class="page-header">
<h2>Chapter1 <small>Hello,World</small></h2>
</div>
</div>
<div class="container">
<div class="jumbotron">
<h1>Hello, {{name}}</h1>
<label for="name">Enter Your Name</label>
<input type="text" ng-model="name" class="form-control input-lg" id="name">
</div>
</div>
</body>
</html>
The angularjs codes:
function AppCtrl($scope){
$scope.name = "World";
});
the result is that the {{name}} model part can not get the correct data. No default data "World" can be shown, and no matter what I type inside the input text box, the output view is always Hello, {{name}}
EDIT: I refer to a book about angularjs. And the demo case shows that the usage I post here. But I found workaround now.
Your Angular is not bootstrapped. Use:
angular.module('App', [])
.controller('AppCtrl', function($scope) {
$scope.name = "World";
});
I suggest you to read through some basic tutorials first.
Check this working demo: JSFiddle

Change AngularJS urls with ng-model

Is there any way to change AngularJS urls with ng-model?
var scotchApp = angular.module('scotchApp', ['ngRoute']);
scotchApp.controller('mainController', function($scope) {
$scope.gettext = function (){
};
});
<!-- index.html -->
<!DOCTYPE html>
<html ng-app="scotchApp">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" />
<link rel="stylesheet" href="https://netdna.bootstrapcdn.com/font-awesome/4.0.0/css/font-awesome.css" />
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular-route.js"></script>
<script src="eventChange.js"></script>
</head>
<body ng-controller="mainController">
<div class="container">
<div class="row">
<div class="col-sm-1">Search</div>
<div class="col-sm-3"><input type="text" class="form-control" ng-model="search" ng-change="gettext()"></div>
</div>
</div>
</body>
</html>
I need to change the URL into something like this http://localhost/angulRoute/search=myVal when user type 'myVal' in the search box (actually inside gettext() function with search value)
You can do something like this in your controller:
$scope.query = $location.search().q;
$scope.$watch('query', function(newValue) {
$location.search('q', newValue);
});
You'd need to inject $location into your controller, and make sure in your route config includes:
reloadOnSearch: true
That would result in a URL like http://localhost/myRoute?q=myVal
Note: I would also add ng-model-options="{updateOn:'blur'}" to your input, to prevent updating the URL on every key press.
EXAMPLE
Here is a working example of how to do this: http://plnkr.co/edit/tphqPeJ0dO74Ux7WpXlU?p=preview
Note that, because of the way plnkr.co works, you won't see the URL changes in the address bar on that site. If you download the code and run it locally, the URL would be updated in the address bar.
Hi I found a javascript solution for that.
$scope.gettext = function (search){
window.history.pushState("object or string", "Title", "/angulRoute/search="+search);
};
with <input type="text" class="form-control" ng-model="search" ng-change="gettext(search)" > worked for me. However anyone have an AngulerJs solution they are welcome :D

Looping through/updating data using AngularJS

I am trying to write a webapp that will retrieve a set of orders from a backend database, display each order to the user one by one allowing update before moving on to the next order.
Is this feasible using purely AngularJS or would I need to contemplate jQuery as well? I can display all the orders in an ng-repeat but I would rather only display them one at a time.
EDIT
The PHP below will return a number of records in the form
[{round:1, name:"Mr Smith", house:22, road:"The Street", year:2013, period:10, result:"O", amount:20}...]
to the controller NewOrderCtrl.
What I would like to know is how to loop through each record retrieved, display the data in the ng-view so that it can be updated, submit and the next record displayed.
JS
var orderApp = angular.module('orderApp',['ngRoute']);
orderApp.config(function($routeProvider,$locationProvider) {
$locationProvider.html5Mode(true);
$routeProvider
.when("/neworder", {templateUrl: "partials/neworder.html", controller:"NewOrderCtrl"})
.otherwise({redirectTo: '/'});
});
function NewOrderCtrl($scope,$http) {
$http.get('php/get_orders.php')
.success(function(data) {
$scope.order = data;
});
};
PHP
<?php
include 'conn.php';
$rs = mysql_query("SELECT d.id,
d.number AS round,
c.name,
c.house,
c.road,
o.year,
o.period,
o.result,
o.amount
FROM tbldrop d
LEFT JOIN vwcustomer c
ON d.customer = c.id
LEFT JOIN tblorder o
ON d.customer = o.customer
WHERE d.number > 0
ORDER BY d.number, d.position");
$items = array();
while($row = mysql_fetch_object($rs)){
$items[] = $row;
}
echo json_encode($items);
?>
neworder.html (currently displays all records retrieved)
<div ng-controller="NewOrderCtrl">
<div ng-repeat="customer in order">
<div>
<span ng-bind="customer.name"></span><br/>
<span ng-bind="customer.house"></span>
<span ng-bind="customer.road"></span><br/>
</div>
<form role="form">
<div class="form-group">
<label for="result" class="control-label">Result:</label>
<div>
<input type="text" ng-model="customer.result" placeholder="Enter result">
</div>
</div>
<div class="form-group">
<label for="amount" class="control-label">Amount:</label>
<div>
<input type="text" ng-model="customer.amount" placeholder="Enter amount">
</div>
</div>
</form>
</div>
</div>
index.html
<!DOCTYPE html>
<html lang="en" ng-app="orderApp">
<head>
<base href="/rounds/">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="css/bootstrap.css"/>
<link rel="stylesheet" href="css/style.css"/>
<title>Rounds</title>
</head>
<body>
<div class="container">
<ng-view></ng-view>
</div>
</div>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular-route.js"></script>
<script type="text/javascript" src="js/app.js"></script>
<script type="text/javascript" src="js/controllers.js"></script>
</body>
</html>
In order to give a complete answer, we would need some code samples or even a jsfiddle to play with, but as a generic answer, yes this is entirely possible with only angularjs.
With the extremely limited amount of information I have, I would suggest doing something like this:
Controller:
$scope.items = [];
$http({method: 'GET', url: '/someUrl'}).success(function(data) {
$scope.items = data;
});
$scope.itemIndex = 0;
$scope.nextItem = function() {
if ($scope.items[$scope.itemIndex + 1]) {
$scope.itemIndex++;
}
};
HTML:
{{ items[itemIndex] }}
<button ng-click="nextItem()">Next</button>
Here's a JSFiddle using $timeout instead of $http to simulate the server response time: http://jsfiddle.net/Z5chE/

Can't create Angular JS module in Coffeescript

I have the following html:
<!DOCTYPE html>
<html>
<head>
<title>Angular JS</title>
<script type="text/javascript" src="/javascripts/app.js"></script>
</head>
<body>
<div ng-app="myApp">
<div ng-controller="FirstController">
<input type="text" ng-model="data.message">
<h1>{{data.message}}</h1>
</div>
<div ng-controller="SecondController">
<input type="text" ng-model="data.message">
<h1>{{data.message}}</h1>
</div>
</div>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
</body>
</html>
and the following coffeescript:
window.myApp = angular.module 'myApp', []
myApp.factory 'Data', ->
return message : 'I am data from a factory'
myApp.controller 'FirstController', ($scope, Data) ->
$scope.data = Data
myApp.controller 'SecondController', ($scope, Data) ->
$scope.data = Data
When I run the app, it prints out {{data.message}} instead of the text I type in the input box. When I remove the module dependency from the html and get data from a parent within the div, it works fine. This leads me to believe that the module is not getting created. What is the problem with my code?
You need to put the script tag that's in the head after the library script.

Resources