I am new to Angular JS and have getting below error when I have tried to inject $http service in the project. Please see the code file below.
As you can see I have created a <ng-app="myapp"> and created a controller for the same. As described in the tutorial I have registered the controller in the View.js and tried to load 'data.json' file data. However, during running the program I am getting error as $http is not defined.
View.html
<!DOCTYPE html>
<html lang="en">
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script>
<script src="js/View.js"></script>
</head>
<body ng-app="myapp">
<div ng-controller="Object">
<span ng-bind="o.rollNo"></span>
<span ng-bind="o.firstName"></span>
<span ng-bind="o.middleName"></span>
<span ng-bind="o.lastName"></span>
<span ng-bind="o.className"></span>
<span ng-bind="o.schoolName"></span>
</div>
</body>
</html>
View.js
var app=angular.module("myapp", []);
app.controller('Object',function($scope,$http) {
$http.get("data.json")
.success( function(response) {
$scope.o= response;
});
});
data.json:
[
{
"rollNo" : "1",
"firstName" : "ABC",
"middleName" : "DEF"
"lastName" : "HIJ"
"className" : "First"
"schoolName" : "CRB"
}
]
Project Structure
No problem with your code, it's working properly.
Since you have only 1 object, you need to get values based on index i.e o[0].rollNo
<body ng-app="myapp">
<div ng-controller="Object">
<span ng-bind="o[0].rollNo"></span>
<span ng-bind="o[0].firstName"></span>
<span ng-bind="o[0].middleName"></span>
<span ng-bind="o[0].lastName"></span>
<span ng-bind="o[0].className"></span>
<span ng-bind="o[0].schoolName"></span>
</div>
</body>
Controller
var app=angular.module("myapp", []);
app.controller('Object',function($scope,$http) {
$http.get('data.Json').
success(function(data, status, headers, config) {
alert("Success");
$scope.o = data;
}).
error(function(data, status, headers, config) {
alert("Error");
// log error
});
});
data.Json
You need to add comma between each key:value
[
{
"rollNo" : "1",
"firstName" : "ABC",
"middleName" : "DEF",
"lastName" : "HIJ",
"className" : "First",
"schoolName" : "CRB"
}
]
As per your project structure, your json file path(js/data.json)
$http.get('js/data.Json').
success(function(data, status, headers, config) {
alert("Success");
$scope.o = data;
}).
error(function(data, status, headers, config) {
alert("Error");
// log error
});
Since this was not yet mentioned in an answer, only in two comments:
You might need to move the line
<script src="js/View.js"></script>
to the bottom
<span ng-bind="o[0].schoolName"></span>
</div>
<script src="js/View.js"></script>
</body>
</html>
... see also #Pratap's answer concerning the JSON file.
Try this:
var app=angular.module("myapp", []);
app.controller('Object', objectCtrl);
objectCtrl.$inject = ['$scope', '$http'];
function objectCtrl($scope, $http){
$http.get("data.json")
.success( function(response) {
$scope.o= response;
});
}
Related
I would like to populate a select with an array in AngularJS.
I have an error : TypeError: meanService.getMeanStuff is not a function but I don't find where is the problem...
This is my view :
<div id="idName" ng-controller="controllerName">
Here is my select :
<select ng-model='modelTypeSelect' ng-options="n for n in meanStuff track by n"></select>
</div>
Controller :
d3DemoApp.controller('controllerName',function($rootScope,$scope, meanService) {
$scope.meanStuff = meanService.getMeanStuff();
$scope.$watch('modelTypeSelect',function(newVal){
$rootScope.$broadcast(':parameterName',{choice:newVal});
});
});
Service :
d3DemoApp.service('meanService', function() {
this.getMeanStuff = function() {
return (["data1", "data2", "data3"])
};
}).service('dataService', function AppCtrl($http, $q) {
this.getCommitData = function(param) {
var deferred = $q.defer();
$http({
method: 'GET',
url: param
}).
success(function(data) {
deferred.resolve({
chartData: data,
error: ''
});
}).
error(function(data, status) {
deferred.resolve({
error: status
});
});
return deferred.promise;
};
});
Thanks.
You have wrong order of scripts first you need to include angular then create the module then include your controllers that use d3DemoApp module:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
<script>
var d3DemoApp = angular.module('d3DemoApp', []);
</script>
<script src="ControllerFilterListType.js"></script>
<script src="ServiceFilterListType.js"></script>
https://plnkr.co/edit/bm8UOrT1mjJyJguAXUUy?p=preview
Removed the brackets around the return. So:
return ["data1", "data2", "data3"]
Okay I'm going to keep this as short as possible.
I've been studying Angular for a bit now and there's still a lot I need to learn, right now I'm trying to figure out how to connect end to end with headers in a service which is completely new to me as I've never done end to end integration.
The code below is provided from another stack overflow answer and what I want to know is how do I connect what they have with say dataService.js. This is all new to me so I'm trying to ask this the best way possible.
<!DOCTYPE html>
<html >
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
</head>
<body ng-app="app">
<div ng-controller="gridController">
<!-- Initialise the grid with ng-init call -->
<div ui-grid="gridOptions" ng-init="GetGridData(urlList)">
</div>
</div>
<script src="Scripts/ng/angular.min.js"></script>
<script src="Scripts/ng-grid/ui-grid.min.js"></script>
<link rel="Stylesheet" type="text/css" href="Scripts/ng-grid/ui-rid.min.css" />
<script type="text/javascript">
var app = angular.module('app', ['ui.grid']);
app.controller("gridController",
["$scope", "$attrs", "$element", "$compile", "$http", "$q",
function ($scope, $attrs, $element, $compile, $http, $q)
{
$scope.urlList = "YourSourceUrl";
function fnGetList(url)
{
var deferred = $q.defer();
$http.get(url)
.success(function (data)
{
deferred.resolve(data);
})
.error(function (errorMessage)
{
alert(errorMessage);
deferred.reject;
});
return deferred.promise;
};
$scope.GetGridData = function (url)
{
console.log("In GetGridData: " + "Getting the data");
// Test Only - un-comment if you need to test the grid statically.
//$scope.loadData = ([
// {
// "UserName": "Joe.Doe",
// "Email": "Joe.Doe#myWeb.com"
// },
// {
// "UserName": "Jane.Doe",
// "Email": "Jane.Doe#myWeb.com"
// },
//]);
//return;
fnGetList(url).then(function (content)
{
// Assuming your content.data contains a well-formed JSON
if (content.data !== undefined)
{
$scope.loadData = JSON.parse(content.data);
}
});
};
$scope.gridOptions =
{
data: 'loadData',
columnDef:
[
{ field: 'UserName', name: 'User' },
{ field: 'Email', name: 'e-mail' }
]
};
}
]);
</script>
</body>
Provided from: How do I get data to show up in angular ui.grid from an $http request
The method I use is to pass the URL as an AJAX call and then wait for the data to get back after which I connect the JSON data to the ng-grid. Note that there will be a delay in getting the data back from the URL and you will have to have a timer that will keep checking for the data return begin valid.
function setCar(){
$.ajax({
type: "POST",
url: '/Test/ConfigConnect.json?details=&car='+car+'&id=1',
dataType: 'json',
success: function(data){
configData = data;
}
});}
The timer function that is part of the javascirpt is also given below.
var timer = setInterval(function() {
$scope.$apply(updatePage);
}, 500);
var updatePage = function() {
if (typeof configData !== 'undefined')
{
clearInterval(timer);
$scope.loadData = configData;
}
};
i'm using the auto-complete in tags-input but when i start writing i get this error: array1.filter is not a function. This is my angular call
$scope.loadTags = function(query) {
var searchPeople = $scope.baseUrl + "&searchString=";
return $http.get(searchPeople + query, {
}).success(function (data) {
$scope.people = data.data.data;
console.log($scope.people);
}).error(function (data){
console.log("Error");
});
};
moreover i don't know how to retrieve a value from, in my case $scope.people json that is something like:
{
"id": 17,
"cod": "gg117",
"name": "Alex"
}
i know that i need a custom template but as long as i get the error i can't do it. By the way the template is this one but i don't know if it's correct
<script type="text/ng-template" id="my-custom-template">
<div class="left-panel">
<img ng-src="./img/avatar.jpeg" />
</div>
<div class="right-panel">
<span ng-bind-html="$highlight($getDisplayText())"></span>
<span>({{people.name}})</span>
</div>
</script>
you need to pass a promise, with data of the format
{
"data":[{'text':'tag1'}, {'text', 'tag1'}]
}
See solution below:
I'm trying to connect to a Parse.com Rest backend and display data from object values.
HTML (I put several angular calls to be sure to catch output):
<div ng-controller="MyController">
<p>{{item}}<p>
<p>{{items}}<p>
<p>{{item.firstName}}<p>
<p>{{data}}<p>
</div>
JAVASCRIPT rest:
function MyController($scope, $http) {
$scope.items = [];
$scope.getItems = function() {
$http({method : 'GET',url : 'https://api.parse.com/1/classes/Professional/id', headers: { 'X-Parse-Application-Id':'XXXX', 'X-Parse-REST-API-Key':'YYYY'}})
.success(function(data, status) {
$scope.items = data;
})
.error(function(data, status) {
alert("Error");
});
};
}
This won't work, it does strictly nothing, not even a message in the console.
I know the rest call got the correct credential, as I'm able to get object content returned when I test it with a rest tester program. Maybe the URL should not be absolute ?
Any clue is very welcome, i've spent DAYS on that.
SOLUTION:
Thanks to the help of people answering this thread, I was able to find the solution to this problem so I just wanted to contribute back:
Get Json object data from Parse.com backend, pass it authentification parameters:
function MyController($scope, $http) {
$scope.items = [];
$scope.getItems = function() {
$http({method : 'GET',url : 'https://api.parse.com/1/classes/Professional', headers: { 'X-Parse-Application-Id':'XXX', 'X-Parse-REST-API-Key':'YYY'}})
.success(function(data, status) {
$scope.items = data;
})
.error(function(data, status) {
alert("Error");
});
};
Notice that ' ' necessary arround header key object values. Those ' ' are not necessary around method and url keys.
Template that list all 'firstName' of each object:
<div ng-controller="MyController" ng-init="getItems()">
<ul>
<li ng-repeat="item in items.results"> {{item.firstName}} </li>
</ul>
</div>
Notice: "item in items.results". "results" is necessary because the return value is a JSON object that contains a results field with a JSON array that lists the objects. This could save you some headache.
Also notice "ng-init": if you don't put that, or any other form of call to the getItem(),then nothing will happen and you will be returned no error.
That was my first try of Angularjs, and i'm already in love ^^.
Based in your request the controller should be:
HTML
<div ng-controller="MyController">
<button type="button" ng-click="getItems()">Get Items</button>
<ul>
<li ng-repeat="item in items"> item.firstName </li>
</ul>
</div>
JS
function MyController($scope, $http) {
$scope.items = []
$scope.getItems = function() {
$http({method : 'GET',url : 'https://api.parse.com/1/classes/Users', headers: { 'X-Parse-Application-Id':'XXXXXXXXXXXXX', 'X-Parse-REST-API-Key':'YYYYYYYYYYYYY'}})
.success(function(data, status) {
$scope.items = data;
})
.error(function(data, status) {
alert("Error");
})
}
}
Just a little update to the newer versions of Angular (using .then since version 1.5):
myApp.controller('MyController', function($scope, $http) {
$scope.items = []
$http({
method: 'GET',
url: 'https://api.parse.com/1/classes/Users',
headers: {'X-Parse-Application-Id':'XXXXXXXXXXXXX', 'X-Parse-REST-API-Key':'YYYYYYYYYYYYY'}
})
.then(function successCallback(response) {
alert("Succesfully connected to the API");
$scope.items = data;
}, function errorCallback(response) {
alert("Error connecting to API");
});
});
var app = angular.module("app",[]);
app.controller("postcontroller", function($scope, $http){
$scope.getAllProjects = function() {
var url = 'https://reqres.in/api/products';
$http.get(url).then(
function(response) {
$scope.projects = response.data.data;
},
function error(response) {
$scope.postResultMessage = "Error with status: "
+ response.statusText;
});
}
$scope.getAllProjects();
});
<div ng-app="app">
<div ng-controller="postcontroller">
<div class="panel-body">
<div class="form-group">
<label class="control-label col-sm-2" for="project">Project:</label>
<div class="col-sm-5">
<select id="projectSelector" class="form-control">
<option id="id" ng-repeat="project in projects"
value="{{project.id}}">{{project.name}}</option>
</select>
</div>
</div>
</div>
</div>
</div>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.js"></script>
Overview
I am building an app (running on MAMP) that holds contact information that will expand to hold more data such as project name & deadline, once this part is functional.
Questions
When the user visits /projects.php#/project/ I would like them to see a list of all the project names with a link to their detail page.
How should I write the following to access all of my data?
Do I need the .json at the end?
What does the #id do?
return $resource('data/project.json/:id', {id: '#id'});
When the user visits /projects.php#/project/a-gran-goodn I would like them to see the details about this project(for now, just the name & address).
How should I write the following to return my data by Id?
$scope.project = $routeParams.id ? Project.get({id: $routeParams.id}): new Project();
plunkr file
http://plnkr.co/edit/7YPBog
project.json
This file lives on http://localhost:8888/angularjs/ProjectsManager/data/project.json
[
{ "address" : [ " 3156 Dusty Highway",
" Teaneck New Jersey 07009-6370 US"
],
"id" : "a-gran-goodn",
"name" : "Grania Goodner",
"phone" : " (862) 531-9163"
},
{ "address" : [ " 62 Red Fawn Moor",
" Rodney Village West Virginia 25911-8091 US"
],
"id" : "b-aime-defranc",
"name" : "Aimery Defranco",
"phone" : " (681) 324-9946"
}
]
app.js
var projectsApp = angular.module('projects', ['ngResource']);
projectsApp.config(function($routeProvider) {
$routeProvider
.when('/', {
controller: 'ProjectListCtrl',
templateUrl: 'partials/projectlist.html'})
.when('project/:id', {
controller: 'ProjectDetailCtrl',
templateUrl: 'partials/projectdetail.html'
})
.otherwise('/');
});
projectsApp.factory('Project', function($resource) {
return $resource('data/project.json/:id', {id: '#id'});
});
projectsApp.controller('ProjectListCtrl', function(Project, $scope) {
$scope.projects = Project.query();
console.log($scope.projects);
});
projectsApp.controller('ProjectDetailCtrl', function(Project, $routeParams, $scope) {
$scope.project = $routeParams.id
? Project.get({id: $routeParams.id})
: new Project();
});
partials/projectlist.html
Add new item
<ul class="unstyled">
<li ng-repeat="project in projects">
<div class="well">
<h2><small>{{project.id}}</small> {{project.name}}</h2>
View Info for {{project.name}}
</div>
</li>
</ul>
partials/projectdetails.html
<h3>Information</h3>
<p>Name: {{project.name}}</p>
<p>Phone Number: {{project.phone}}</p>
<p ng-repeat="line in project.address">{{line}}</p>
index.php
<?php
header('Access-Control-Allow-Origin: *');
?>
<!doctype html>
<html ng-app="projects">
<head>
<meta charset="utf-8">
<title ng-bind="title" ng-cloak>Restaurant —</title>
<link href="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.no-icons.min.css" rel="stylesheet">
</head>
<body ng-controller="ProjectListCtrl">
<a class="brand" href="#">Projects Manager</a>
<div id="app-container" class="container-fluid">
<div class="row-fluid">
<div class="span12" id="main" ng-view>
</div><!--/.span12-->
</div><!--/.row-fluid-->
<footer>Copyright Projects © 2013</footer>
</div><!--/.container-->
<script src="http://code.jquery.com/jquery-1.10.0.min.js"></script>
<script src="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>
<!-- Don't forget to load angularjs AND angular-resource.js -->
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular-resource.js></script>
<!--Controllers-->
<script src="app.js"></script>
</body>
</html>
Since you can't query against a raw JSON file like you can with RESTful-style URLs (which is what $resource is built to do), you can instead get a copy of the JSON and then build your own query, get, etc. that looks at the data and returns the right thing. It's a bit tricky because you also want to support new Project, which doesn't really make sense when using a file-backed store, but this example supports it:
projectsApp.factory('Project', function($http) {
// Create an internal promise that resolves to the data inside project.json;
// we'll use this promise in our own API to get the data we need.
var json = $http.get('project.json').then(function(response) {
return response.data;
});
// A basic JavaScript constructor to create new projects;
// passed in data gets copied directly to the object.
// (This is not the best design, but works for this demo.)
var Project = function(data) {
if (data) angular.copy(data, this);
};
// The query function returns an promise that resolves to
// an array of Projects, one for each in the JSON.
Project.query = function() {
return json.then(function(data) {
return data.map(function(project) {
return new Project(project);
});
})
};
// The get function returns a promise that resolves to a
// specific project, found by ID. We find it by looping
// over all of them and checking to see if the IDs match.
Project.get = function(id) {
return json.then(function(data) {
var result = null;
angular.forEach(data, function(project) {
if (project.id == id) result = new Project(project);
});
return result;
})
};
// Finally, the factory itself returns the entire
// Project constructor (which has `query` and `get` attached).
return Project;
});
You can use the results of query and get like any other promise:
projectsApp.controller('ProjectListCtrl', function(Project, $scope) {
$scope.projects = Project.query();
});
projectsApp.controller('ProjectDetailCtrl', function(Project, $routeParams, $scope) {
$scope.project = $routeParams.id
? Project.get($routeParams.id)
: new Project();
});
Note the change to Project.get($routeParams.id); also, the updated Plunker also fixes a problem in your $routeProvider configuration.
This is all demonstrated here: http://plnkr.co/edit/mzQhGg?p=preview
i will paste here a generic code i use to fetch json from your local or a remoteserver maybe it will help you:
it uses a factory that you can call when you need it.
app.factory('jsonFactory', function($http) {
var jsonFactory= {
fromServer: function() {
var url = 'http://example.com/json.json';
var promise = $http.jsonp(url).then(function (response) {
return response.data;
});
return promise;
},
hospitals: function() {
var url = 'jsons/hospitals.js';
var promise = $http.get(url).then(function (response) {
return response.data;
});
return promise;
}
};
return jsonFactory;
});
Then when you need to call it:
function cardinalCtrl(jsonFactory, $scope, $filter, $routeParams) {
jsonFactory.hospitals().then(function(d){
$scope.hospitals=d.hospitals;
});
jsonFactory.fromServer().then(function(d){
$scope.fromServer=d.hospitals;
});
}