Angular get JSON data with ajax - angularjs

How can I get json data via ajax with angular? I tried a lot but my code is not working.
My code:
<!DOCTYPE html>
<html lang="en" ng-app="test">
<head>
<meta charset="UTF-8">
<title></title>
<script src="https://code.angularjs.org/1.6.1/angular.min.js"></script>
<script>
angular.module('test', [])
.controller('TestCtrl', function($scope, $http) {
$scope.data = [];
$http.get("http://jsonplaceholder.typicode.com/users").then(function(res) {
$scope.data = JSON.parse(res);
});
});
</script>
</head>
<body ng-controller="TestCtrl">
<div ng-repeat="item in data">
{{item.id}}
</div>
</body>
</html>

Did you try like this..
<script>
var app = angular.module('test', [])
app.controller('TestCtrl', function ($scope, $http) {
$http.get("http://jsonplaceholder.typicode.com/users").then(function(res,status,xhr) {
$scope.data = res.data;
});
});
</script>

Related

Angular Controller is not triggering

My controller is not triggering. It should be stupid but I can't see why.
Here find my code structure.
Please help me find that basic error.
template :
<!DOCTYPE html>
<html ng-app="attachmentsApp" ng-cloak="">
<head>
<meta charset="utf-8"/>
<script th:inline="javascript">
/*<![CDATA[*/
var source = [[${source}]];
var appContext = /*[[#{/}]]*/ '';
/*]]>*/
</script>
</head>
<body>
<div th:replace="include"></div>
<script th:src="#{/app/modules/attachments/scripts/attachmentsapp.js}"></script>
<script th:src="#{/app/modules/attachments/scripts/controllers/AttachmentsHomeCtrl.js}"></script>
<script th:src="#{/app/modules/attachments/scripts/services/AttachmentsHomeService.js}"></script>
</body>
</html>
App :
angular
.module('attachmentsApp', ['ngRoute'
]).run(['$rootScope', function($rootScope){
$rootScope.appContext = window.appContext;
$rootScope.language = window.language;
$rootScope.source = window.source;
}])
.config(function($routeProvider) {
$routeProvider.when('/', { templateUrl: window.appContext + 'app/modules/attachments/views/home.html', controller: "AttachmentsHomeCtrl" })
});
Controller:
angular.module('attachmentsApp').controller('AttachmentsHomeCtrl', ['$scope','$rootScope','AttachmentsHomeService','$window',
function ($scope,$rootScope,AttachmentsHomeService,$window) {
console.log($rootScope.source);
debugger;
}]);
Service :
'use strict';
angular.module('attachmentsApp').service('AttachmentsService', [ '$http', '$rootScope', function($http, $rootScope){
this.getForm = function(type) {
debugger;
}
return this;
}]);
Many thanks
Suggesting some change in your HTML:
1) Define and load files before their use: ng-app was being used before attachmentsapp.js file is loaded in DOM
2) Order of usage: service file was loaded after its usage in controller
It should be look like:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<script th:inline="javascript">
/*<![CDATA[*/
var source = [[${source}]];
var appContext = /*[[#{/}]]*/ '';
/*]]>*/
</script>
<script th:src="#{/app/modules/attachments/scripts/attachmentsapp.js}"></script>
<script th:src="#{/app/modules/attachments/scripts/services/AttachmentsHomeService.js}"></script>
<script th:src="#{/app/modules/attachments/scripts/controllers/AttachmentsHomeCtrl.js}"></script>
</head>
<body ng-app="attachmentsApp" ng-cloak="">
<div th:replace="include"></div>
</body>
</html>
Not 100% sure, but it should be working. Do a try !!
Moreover, keep an eye on console.
It was the Service name.
AttachmentsHomeService as registering it in Controller
AttachmentsService in service definition
Many thanks for your help

AngularJS not returning data from $http rest request

Any idea what I am doing wrong here?
It must be something simple but I have been trying a bunch of different combinations for hours.
Thanks in advance.
https://plnkr.co/edit/3NkmhLVLTZe3aMoiK9Ff?p=preview
app.js
var app = angular.module('fishHouseMonitorApp', []);
app.controller('fishHouseMonitorController', function($scope, $http) {
$http.get("http://www.eastcentralmdaa.org/fishhousemonitor/api/v1/sensormeasurements")
.then(function(response) {
$scope.sensormeasurements = response.data;
// do some error checking to ensure there is an element 0?
$scope.selectedElement = $scope.sensormeasurements[0];
});
});
index.html
<!DOCTYPE html>
<html ng-app="fishHouseMonitorApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="app.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
</head>
<body>
<div class="container" ng-controller="fishHouseMonitorController">
<div class="row">
<ul class="list-group">
<li class="list-group-item" ng-repeat="sensormeasurement in sensormeasurements" ng-click="selectContact($index)">
<span>{{ sensormeasurement.sensorMeasurementDateTime }}</span>
</li>
</ul>
</div>
</div>
</body>
</html>
This works:
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="customersCtrl">
{{ myData }}
</div>
<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$http.get("https://jsonplaceholder.typicode.com/users").then(function(response) {
$scope.myData = response.data;
});
});
</script>
</body>
</html>
This does not:
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="customersCtrl">
{{ myData }}
</div>
<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$http.get("http://www.eastcentralmdaa.org/fishhousemonitor/api/v1/sensormeasurements").then(function(response) {
$scope.myData = response.data;
});
});
</script>
</body>
</html>
even though https://jsonlint.com/ validates http://www.eastcentralmdaa.org/fishhousemonitor/api/v1/sensormeasurements as valid JSON
You cannot access an HTTP destination while running your application on HTTPS. Change your protocol to HTTPS and you will be fine:
<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$http.get("https://jsonplaceholder.typicode.com/users").then(function(response) {
$scope.myData = response.data;
});
});
</script>
I did not fully understand the problem.I hope this helps
app.js
var app = angular.module('fishHouseMonitorApp', []);
app.controller('fishHouseMonitorController', function($scope, $http) {
$http.get("http://www.eastcentralmdaa.org/fishhousemonitor
/api/v1/sensormeasurements")
.then(function(response) {
$scope.sensormeasurements = response.data[0];
// do some error checking to ensure there is an element 0?
});
});
index.html
<ul class="list-group">
<li class="list-group-item" ng-model="sensormeasurements" ng-click="selectContact($index)">
<span>{{ sensormeasurement.sensorMeasurementDateTime }}</span>
</li>
</ul>

How to use window.onload in angular js controller?

How to use window.onload function inside a controller.
window.onload= function() {
console.log("Hi Page loaded")
};
The controller is not applicable for the full page.
I want to execute a function after my controller loads at-least.
You can use ng-init and invoke your necessary function using the same directive
var app = angular.module('DemoApp', [])
app.controller('akuaController', function($scope) {
$scope.load = function() {
alert("Window is loaded");
}
});
<!DOCTYPE html>
<html>
<head>
<script data-require="angular.js#1.4.7" data-semver="1.4.7" src="https://code.angularjs.org/1.4.7/angular.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-filter/0.4.7/angular-filter.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-app="DemoApp" ng-controller="akuaController">
<div ng-init="load()">
</div>
</body>
</html>
Changing the example from Angular $window
Your Controller
angular.module('windowExample', [])
.controller('ExampleController', ['$scope', '$window', function($scope, $window) {
$scope.greeting = 'Hello, World!';
$scope.doGreeting = function(greeting) {
// This would be a starting point
$window.onload(greeting);
};
}]);
Your markup
<div ng-controller="ExampleController" ng-init="ExampleController.doGreeting()">
</div>
//inside your controller
$scope.$on('$viewContentLoaded', function() {
// write here
// either methods or variables
});

Injecting $routeParams into controller

I'm trying to pull some data out of url to pass into a controller for use in the controller. I've been trying to do it via Angular Routing.
<!DOCTYPE html>
<html ng-app>
<head>
<meta name="viewport" content="width=device-width" />
<title>Edit</title>
<script src="~/Scripts/angular.min.js"></script>
</head>
<body>
<div ng-controller="SearchController" >
<input type="text" ng-model="SearchText" />
</div>
<script type="text/javascript">
var app = angular.module('myApp', ['ngRoute']);
app.config(function ($locationProvider, $routeProvider) {
$locationProvider.html5Mode(true);
$routeProvider
.when('/angularroute/edit/:sometext', {
controller: 'SearchController'
});
});
app.controller("SearchController", ['$scope', '$routeParams', SearchController]);
function SearchController($scope, $routeParams) {
$scope.SearchText = $routeParams.sometext;
}
SearchController.$inject = ['$scope'];
</script>
</body>
</html>
<html ng-app>
<head>
<meta name="viewport" content="width=device-width" />
<title>Edit</title>
<script src="~/Scripts/angular.min.js"></script>
</head>
<body>
<div ng-controller="SearchController" >
<input type="text" ng-model="SearchText" />
</div>
<script type="text/javascript">
var app = angular.module('myApp', ['ngRoute']);
app.config(function ($locationProvider, $routeProvider) {
$locationProvider.html5Mode(true);
$routeProvider
.when('/angularroute/edit/:sometext', {
controller: 'SearchController'
});
});
app.controller("SearchController", ['$scope', '$routeParams', SearchController]);
function SearchController($scope, $routeParams) {
$scope.SearchText = $routeParams.sometext;
}
SearchController.$inject = ['$scope'];
</script>
</body>
</html>
$routeParams in the controller is always null. Why?
Secondly, the url of the page that this is used on will be something like this: http://www.blah.com/angularroute/edit/32432 Is this an appropriate use of Angular routing?
Hi it looks like you miss reference to angular-route.js script please see example here: http://plnkr.co/edit/RZxt3t9dNQxbyW94V9jQ?p=preview
JS:
var app = angular.module('app', ['ngRoute']);
app.config(function($locationProvider, $routeProvider) {
$routeProvider
.when('/angularroute/edit/:sometext', {
controller: 'SearchController',
templateUrl: 'http://run.plnkr.co/d8ZBAv3VEkfIJI4h/search.html'
});
$locationProvider.html5Mode(true);
});
app.controller('firstCtrl', function($scope) {
});
app.controller("SearchController", ['$scope', '$routeParams', SearchController]);
function SearchController($scope, $routeParams) {
console.log($routeParams);
$scope.SearchText = $routeParams.sometext;
}
html:
<!DOCTYPE html>
<html>
<head>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular-route.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-app="app">
<div ng-controller="firstCtrl">
Search for elephant<br/>
Search for horse<br/>
Search for tigger<br/>
</div>
<div ng-view="">
</div>
</body>
</html>
Had the same problem with AngularJS 1.3.0, updating to 1.3.13 fixed it.

sharing a var between views/controllers

I know this question has been asked 100s of times but i have yet to succeed in implementing this after reading countless of threads... shame on me.
I know this is a lot of code (sorry). But I just can't find what I'm doing wrong,
So to the problem I want to add something to the list in pat1 then click over to pat2 and see the same list.
Routing;
var routeApp = angular.module('routeApp', ['ngRoute', 'rootMod']);
routeApp.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/pat1', {
templateUrl: 'partials/pat1.html',
controller: 'pageOneCont'
}).
when('/pat2', {
templateUrl: 'partials/pat2.html',
controller: 'pageTwoCont'
}).
otherwise({
redirectTo: '/pat1'
});
}]);
Controllers & Service:
var rootMod = angular.module('rootMod', []);
rootMod.controller('pageOneCont', [ 'serv', '$scope', function (serv, $scope) {
'use strict';
// Your controller implementation goes here ...
$scope.handleClick = function ($scope, serv){
var updateFoo = function(){
$scope.foo = serv.foo;
};
aService.registerObserverCallback(updateFoo);
//service now in control of updating foo
};
}]);
rootMod.controller('pageTwoCont', [ 'serv', '$scope', function (serv, $scope) {
'use strict';
// Your controller implementation goes here ...
$scope.handleClick = function ($scope, serv){
var updateFoo = function(){
$scope.foo = serv.foo;
};
aService.registerObserverCallback(updateFoo);
//service now in control of updating foo
};
}]);
/* Service */
rootMod.factory('serv', [ function () {
var observerCallbacks = [];
//register an observer
this.registerObserverCallback = function(callback){
observerCallbacks.push(callback);
};
//call this when you know 'foo' has been changed
var notifyObservers = function(){
angular.forEach(observerCallbacks, function(callback){
callback();
});
};
}]);
INDEX.html
<!doctype html>
<html lang="en" ng-app="routeApp">
<head>
<script src="lib/angular/angular.js"></script>
<script src="lib/angular/angular-route.js"></script>
<script src="js/app.js"></script>
<script src="js/controllers.js"></script>
</head>
<body>
<li> ONE </li>
<li> TWO </li>
</body>
<!-- SinglePage -->
<div ng-view></div>
</html>
PAT1.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Angular Test</title>
<link rel="stylesheet" href="css/app.css">
<link rel="stylesheet" href="css/bootstrap.css">
<script src="lib/angular/angular.js"></script>
<script src="js/controllers.js"></script>
</head>
<div ><!--ng-app="myModule" ng-controller="ContactController">-->
<h1> ONE </h1>
<button ng-click="handleClick"> BROADCAST </button>
<div ng-repeat="item in foo">{{ item }}</div>
</div>
</html>
PAT2.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Angular Test</title>
<link rel="stylesheet" href="css/app.css">
<link rel="stylesheet" href="css/bootstrap.css">
<script src="lib/angular/angular.js"></script>
<script src="js/controllers.js"></script>
</head>
<div> <!--ng-app="myModule" ng-controller="ContactController">-->
<h1> TWO </h1>
<div ng-repeat="item in foo">{{ item }}</div>
</div>
</html>
JS
Your service is injected as serv in your controllers but you call aService. Use serv instead.
You should use rootMod.service() instead of rootMod.factory() since you are using this and not returning anything in your service function (see this for the difference between factories and services).
There is no serv.foo property. You have to add this.foo = /** something **/; to your service function.
So this should work:
var rootMod = angular.module('rootMod', []);
rootMod.controller('pageOneCont', [ 'serv', '$scope', function (serv, $scope) {
'use strict';
// Your controller implementation goes here ...
$scope.handleClick = function ($scope, serv){
var updateFoo = function(){
$scope.foo = serv.foo;
};
serv.registerObserverCallback(updateFoo);
// service now in control of updating foo
};
}]);
rootMod.controller('pageTwoCont', [ 'serv', '$scope', function (serv, $scope) {
'use strict';
// Your controller implementation goes here ...
$scope.handleClick = function ($scope, serv){
var updateFoo = function(){
$scope.foo = serv.foo;
};
serv.registerObserverCallback(updateFoo);
// service now in control of updating foo
};
}]);
/* Service */
rootMod.service('serv', [ function () {
var observerCallbacks = [];
// call this when you know 'foo' has been changed
var notifyObservers = function(){
angular.forEach(observerCallbacks, function(callback){
callback();
});
};
// initialize foo here
this.foo = '';
// register an observer
this.registerObserverCallback = function(callback){
observerCallbacks.push(callback);
};
}]);
HTML
You put the ng-view container outside of the body. It has to be inside. Also the path to a view starts with #/ so you have to change your links.
<!doctype html>
<html lang="en" ng-app="routeApp">
<head>
<script src="lib/angular/angular.js"></script>
<script src="lib/angular/angular-route.js"></script>
<script src="js/app.js"></script>
<script src="js/controllers.js"></script>
</head>
<body>
<li> ONE </li>
<li> TWO </li>
<!-- SinglePage -->
<div ng-view></div>
</body>
</html>
Each view only needs the content that should be placed inside the ng-view container. So you mustn't make a complete HTML document.
pat1.html
<h1> ONE </h1>
<button ng-click="handleClick"> BROADCAST </button>
<div ng-repeat="item in foo">{{ item }}</div>
pat2.html
<h1> TWO </h1>
<div ng-repeat="item in foo">{{ item }}</div>

Resources