AngularJs 1 not working - javascript

im trying to fetch data from a json file but i doesnt work, i already check every options here but no one works for me, none of the code its working, i dont know if i have to import something else, and the json file its in the same level of the index file, hope you can help me
appClients.js
(function(){
var app = angular.module('customer',[]);
alert('Success');
app.controller("CustomerController",function($scope,$http){
$http.get('../customer.json')
.success(function(data) {
// $scope.phones = data;
alert('Success');
})
.error(function(data){
alert('Error');
});
});
});
index.html
<!DOCTYPE HTML>
<html ng-app="customer">
<head>
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body class="Master" ng-controller="CustomerController as customer">
<script type="text/javascript" src="js/angularjs.min.js"></script>
<script type="text/javascript" src="js/appClients.js"></script>
<header id="MasterHeader">
</header>
<div class="container">
<div class="row">
<div class="col-lg-12">
<div class="col-lg-6" id="CustomerList" ng-repeat="product in customer.clients">
<h3>{{product.id}}</h3>
</div>
<div class="col-lg-6" id="CustomerDetails">Details</div>
</div>
</div>
</div>
<footer id="MasterFooter">
</footer>
</body>
</html>

It looks like your IIFE (Immediately-invoked function expression) is not being executed. Update your appClient.js file to
(function(){
var app = angular.module('customer',[]);
alert('Success');
app.controller("CustomerController",function($scope,$http){
$http.get('../customer.json')
.success(function(data) {
// $scope.phones = data;
alert('Success');
})
.error(function(data){
alert('Error');
});
});
})();
Note the additional () on the final line. This should allow you to see the initial "Success" alert.
If your ajax call then succeeds you would need to make the $scope property that the result is set to consistent with the $scope property referenced in the HTML. Based on the current snippet you seem to be setting the result to $scope.phone in the controller, but reference $scope.customer in your HTML.

Related

Dynamically loading json content within a HTML Script

I am writing a webpage using HTML and javascript. I have written a script (as seen below) that loads records from a json file. My script is meant to load data from the json file and display like a bootstrap alert. When I first ran it, the script worked, but strangely subsequent tests did not work. Does anyone have any ideas to fix this?
index.html:
<!DOCTYPE html>
<html>
<head>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<link type="text/css" href="css/style.css" rel="stylesheet">
<!-- Script in Question -->
<script type="text/javascript">
// This is a way to load data from a JSON file and load it into places in the html document. Based on: https://howtocreateapps.com/fetch-and-display-json-html-javascript/
fetch('alerts.json')
.then(function(response){
return response.json();
})
.then(function (data){
appendData(data);
})
.catch(function (err) {
console.log(err);
});
function appendData(data) {
var container = document.getElementById("alerts");
for (let i = 0; i < data.length; i++) {
var div = document.createElement("div");
div.className = "alert alert-primary";
div.setAttribute("role", "alert")
div.innerHTML = data[i].content;
container.appendChild(div)
}
}
</script>
<title>Guitars</title>
</head>
<body>
<div id="alerts" style="text-align: center;">
<!-- JSON data appears here -->
</div>
<div style="text-align: center;" id="main">
<!-- Other stuff here -->
</div>
<div style="text-align: center;">
<!-- Other stuff here -->
</div>
</body>
</html>
alerts.json:
[
{"content":"Welcome back, test1!"},
{"content":"Welcome back, test2!"},
{"content":"Welcome back, test3!"}
]
The code reads the records from alerts.json and inserts them into a div with an id "alerts" - as seen in the <script> tag. Any help would be greatly appreciated!
OP here. Thanks to user #David, it was suggested to clear out all errors found in the webpage debugging console. Upon clearing these up, the function then worked as intended!

Why is AngularJS printing "> " in ng-repeat

I am trying to get AngularJS to parse all the data given to it in JSON from a Spring rest controller. I am able to get the data to parse and everything but whenever angular repeats in the loop it print a text of "> " on the page.
My javascript
var HOST_SERVER = "http://localhost:8080";
angular.module('exchange', [])
.controller("Book", function ($scope, $http) {
$http.get(HOST_SERVER + "/exchange/get")
.then(function (response) {
$scope.books = response.data;
});
});
The html
<!DOCTYPE html>
<html data-ng-app="exchange">
<head>
<title>The Book Exchange</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js"></script>
<script src="jsengine01.js"></script>
<meta charset="utf-8" />
</head>
<body>
<!-- test stuff-->
<div data-ng-controller="Book">
<div data-ng-repeat="book in books">>
<h1>{{book.title}}</h1>
<h4>By {{book.author}}</h4>
</div>
</div>
</body>
</html>
I tested the controllers and they return the appropriate json responses but I can post those as well if it would be helpful
There is a second > in your code that is being repeated...
<body>
<!-- test stuff-->
<div data-ng-controller="Book">
<div data-ng-repeat="book in books">> <!-- Remove the second '>' -->
<h1>{{book.title}}</h1>
<h4>By {{book.author}}</h4>
</div>
</div>
</body>

How to display data in HTML from http get call using angularJS 1.6

I am able to console the result of the http call but when I bind it so that I can view on the html page I am unable to do it. Can someone help me with this? I am posting the controller code and the html below.
Controller code
//module
var weatherApp = angular.module('weatherApp',['ngRoute' , 'ngResource']);
//Routes
//http://api.openweathermap.org/data/2.5/forecast/daily?APPID=metric
weatherApp.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl:'pages/home.htm',
controller:'homeController'
})
.when('/forecast', {
templateUrl:'pages/forecast.htm',
controller:'forecastController'
});
});
//services
weatherApp.service('cityService' ,function() {
this.city ="San Jose, CA";
});
//controllers
weatherApp.controller('homeController' ,['$scope', 'cityService', function($scope , cityService) {
$scope.city = cityService.city;
$scope.$watch('city' , function () {
cityService.city = $scope.city;
});
}]);
$scope.city = cityService.city;
console.log($scope.city);
$http({
url: "http://api.openweathermap.org/data/2.5/forecast/daily?APPID==metric",
method: "GET",
params: {q: $scope.city, cnt:2}
}).then(function(response){
$scope.weatherResults = response.data;
console.log($scope.weatherResults);
});
}]);
HTML CODE For Index.htm
<!DOCTYPE html>
<html lang="en" ng-app="weatherApp">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="css/navbar.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular-route.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular-resource.min.js"></script>
<script src="app.js"></script>
</head>
<body>
<!-- NAVBAR -->
<nav class="navbar navbar-default">
<div class="container-fluid">
<!-- Brand and toggle get grouped for better mobile display -->
<a class="navbar-brand" href="#">Accurate Weather</a>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav navbar-right">
<li>Home</li>
</ul>
</div><!-- /.navbar-collapse -->
</div><!-- /.container-fluid -->
</nav>
<!-- NAVBAR ENDS-->
<div class="container">
<div ng-view></div>
</div>
</body>
</html>
Code for Forecast.html
Forecast for {{city}} <!-- THIS WORKS -->
{{ weatherResult.cnt }} <!-- THIS DOES NOT WORK -->
Code for home.htm (EVERYTHING WORKS FINE HERE JUST POSTING FOR THE SAKE OF CLARITY)
<div class = "row">
<div class = "col-md-6 col-md-offset-3">
<h4>Forecast by city</h4>
<div class="form-group">
<input type="text" ng-model="city" class="form-control" />
</div>
Get forecast
</div>
</div>
console output correctly displays the objects:
Maybe try and initialize $scope.weatherResult as an empty object in your controller so that AngularJS can watch it correctly.
Just put this assigning inside $scope.apply to notify angular engine that data was changes asynchronously so it should be processed correctly
$scope.$apply(function () {
$scope.weatherResult = response.data; //IF I LOG THIS IT WORKS
});
Also good to add check that gigest cycle is not in progress now
if(!$scope.$$phase) {
//$digest or $apply
}
Angular's inbuilt 2-way data binding does not work on http responses which is a known issue. Use $timeout to manually kick in the 2-way data binding and thereby initiating the digest cycle.
$scope.getWeather= function(){
$http({
url: "http://api.openweathermap.org/data/2.5/forecast/daily?AP&units=metric",
method: "GET",
params: {q: $scope.city, cnt:2}
})
.then(function(response){
$timeout(function(){
$scope.weatherResult = response.data;
}, 0);
});
}
}]);
Note the $timeout timer is set at 0ms to immediately kick in the digest cycle.
Correct Code posted. I was assigning the http get call to $scope.variable, I just removed it and it started working. Thanks

Cannot access http json service in angular js

I am new to angularjs and I want to know why it isn't working.
The code has a flaw and am not sure about the same.
Thinking from java perspective,httpController defined has nested function defined inside.
Here it is my code
index.html
<!DOCTYPE html>
<html >
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body>
<div ng-app="myapp" ng-controller="HelloController">
<h2>{{message}}</h2>
</div>
<div ng-app="httpService" ng-controller="httpController">
<div>FirstName:{{user.name}}</div>
</div>
</body>
</html>
Script.js
var app = angular.module("myapp", []);
app.controller("HelloController", function($scope) {
$scope.message = "Hello, AngularJS";
});
var httpApp=angular.module("httpService",[]);
httpApp.controller("httpController",function($scope,$http){
var onUserComplete=function(response){
$scope.user=""response.data"";
}
$http.get("https://api.github.com/users/rob").then(onUserComplete);
}
);
Only one ng-app will be automatically bootstrapped on your page. That's why if you remove the first ngApp directive, the second one will work.
var httpApp = angular.module("httpService", []);
httpApp.controller("httpController", function($scope, $http) {
var onUserComplete = function(response) {
$scope.user = response.data;
}
$http.get("https://api.github.com/users/rob").then(onUserComplete);
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<div ng-app="httpService" ng-controller="httpController">
<div>FirstName: {{user.name}}</div>
</div>
NOTE: You have a typo in your callback, remove ""s around your response.data. Also, since you are using Angular 1.5.6, you don't need to specify dependencies/inject your $http service to make your code work.
https://plnkr.co/edit/LyWCLeBeyHPzjys3LOcr?p=preview
<body ng-app="httpService">
<div ng-controller="httpController">
<div>FirstName: {{user.key}}</div>
</div>
</body>
This link is working fine...just try it out
Do not use ng-app more than once in your program...Your code would not work

Updating a variable inside Service

Right I've got a really dumb one for you, and I've been looking at this code all day with no result.
I have a simple textbox which goes through a controller and updates a variable inside a service (The service will eventually fetch/update data from somewhere else).
At the moment, I am able to retrieve the variable value all the way to the view and it works, but the textbox is unable to update the variable inside the service in order to then display the new variable value in the view again....
I really appreciate any help and hope I have made sense!!!
// APP/APP.JS
(function(){
var app = angular.module('appMod', ['ngRoute', 'ngAnimate']);
app.config(function ($routeProvider) {
$routeProvider
.when('/',
{
controller: 'introController',
templateUrl: 'app/partials/intro.html'
})
.otherwise({ redirectTo: '/' });
});
app.controller('nameController', function($scope, dataService) {
var nameValue;
this.name = dataService.getName();
this.submitName = function(nameVal) {
nameValue = this.nameCtrl.nameVal;
dataService.setName(nameValue);
};
});
app.controller('introController', function($scope, dataService) {
this.name = dataService.getName();
});
app.service('dataService', function () {
var name = "f";
this.getName = function() {
return name;
};
this.setName = function(nameVal) {
name = nameVal;
};
});
})();
<!-- INDEX.HTML -->
<!DOCTYPE html>
<html ng-app="appMod">
<head>
<link rel="stylesheet" type="text/css" href="content/css/normalize.css">
<link rel="stylesheet" type="text/css" href="content/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="content/css/style.css">
<link rel="stylesheet" type="text/css" href="content/css/animation.css">
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script type="text/javascript" src="scripts/bootstrap.min.js"></script>
<script type="text/javascript" src="scripts/angular.min.js"></script>
<script type="text/javascript" src="scripts/angular-route.min.js"></script>
<script type="text/javascript" src="scripts/angular-timer.min.js"></script>
<script type="text/javascript" src="scripts/angular-animate.min.js"></script>
<script type="text/javascript" src="app/app.js"></script>
</head>
<body>
<div class="container">
<div class="row" ng-controller="nameController as nameCtrl">
<img src="content/images/sitelogo.png" class="logo">
<h2 class="welcomeMessage fade">Welcome <span class="fade" ng-show="!nameCtrl.name == ''">{{nameCtrl.name}}</span><span class="inline fade" ng-hide="nameCtrl.name !== ''">Friend</span> <small>(We like to get personal!)</small></h2>
<div class="namebox fade">
<h2>Welcome <small class="fade">Please type your name</small></h2>
<form class="fade">
<div class="form-group">
<input type="text" class="form-control" ng-model="nameCtrl.nameVal" autofocus>
</div>
<button type="submit" style="width:100%;" class="btn btn-default fade" ng-click="nameCtrl.submitName()" >Submit</button>
</form>
</div>
</div>
</div>
<div ng-view></div>
</body>
</html>
You need to be binding to name and not nameVal on your input
Then just pass that in your setName call, i don't think the rest of the code is needed in there, you can get rid of the nameValue var too.
this.submitName = function() {
dataService.setName(this.name);
};
The nameValue var is local to the controller and not available on the $scope to bind to your view, so even though you were changing it, the view didn't know about it as it couldn't see that var.

Categories

Resources