This is my html
<!DOCTYPE html>
<html x-ng-app="demo">
<head>
<title>Demo</title>
<script src="../demo/js/angular.js"></script>
<script src="../demo/js/jquery-3.1.0.js"></script>
<script src="../demo/js/jquery-3.1.0.min.js"></script>
<script src="../demo/js/bootstrap.js"></script>
<script src="../demo/js/bootstrap.min.js"></script>
<link href="../demo/css/bootstrap.css" rel="stylesheet">
<script src="../demo/js/employee_service.js"></script>
<script src="../demo/js/employee_controller.js"></script>
</head>
<body>
<form name="demo_form">
<div x-ng-controller="EmployeeController">
<h1> {{Employee.name}} </h1>
<span> </span>
<ul>
<li x-ng-repeat="address in employee.addresses">
{{address.address1}}
</li>
</ul>
</div>
</form>
</body>
</html>
This is my service script
var module = angular.module('demo', []);
module.service('EmployeeService', function($http){
this.get = function(id){
var method = "GET";
var url = "http://localhost:8080/rest/employee/get/" + id;
console.log(url);
$http({
method : method,
url : url,
headers: {'Content-Type' : 'application/json'}
}).then(onSuccess, onError);
function onSuccess(response){
console.log('got it');
return response.data;
}
function onError(response){
console.log(response.statusText);
}
}
});
This is my controller
//module.controller('EmployeeController', function ($scope, $routeParams EmployeeService) { //This line give an error but it is not related to the question
module.controller('EmployeeController', function ($scope, EmployeeService) {
//var paramEmployeeID = $routeParams.params1;
var paramEmployeeID = 1;
//Here it doesn't wait for the onSuccess method from the service which will deliver the object.
$scope.employee = EmployeeService.get(paramEmployeeID);
//$scope.employee = angular.copy(EmployeeService.get(paramEmployeeID));
console.log($scope.employee);
});
The error comes when the page loads and starts with the service and then controller. That's why it tries to load first the employee then it doesn't wait for the onSuccess method and it jumps to the controller to continue and finally comes back to the service to execute the onSuccess method which executes too late because it returns the object but in the controller I already got the undefined object. How can I solve this problem?
Async issue. You can chain the promise. Try:
On the service make sure you return the promise:
this.get = function(id){
var method = "GET";
var url = "http://localhost:8080/rest/employee/get/" + id;
console.log(url);
function onSuccess(response){
console.log('got it');
return response.data;
}
return $http({
method : method,
url : url,
headers: {'Content-Type' : 'application/json'}
}).then(onSuccess, onError);
}
In the controller you can chain it to get the data that you need:
EmployeeService.get(paramEmployeeID).then(function(employee){
$scope.employee = employee;
console.log($scope.employee);
});
Related
I am learning Angular JS. I am trying to create a mock portal that displays Daily Messages. I have stored my daily messages in a database table.
create table DailyMsg(Sno int primary key, msg varchar(max));
Then I created a service using factory in AngularJS.
public class DailyMsgsController : Controller
{
private amenEntities1 db = new amenEntities1();
// GET: DailyMsgs
public ActionResult Index()
{
return Json(db.DailyMsgs.ToList(),JsonRequestBehavior.AllowGet);
}
}
I tested the URL and it works fine, it returns the expected data in the JSON format
https://localhost:44329/DailyMsgs
Now, I wanted to display this data on my HomePage. But it doesn't work. On inspecting the page it shows me the error
Error: $http:badreq
Bad Request Configuration
Http request configuration url must be a string or a $sce trusted object. Received: undefined
My Controller
var myApp = angular.module('myApp', []);
//Daily Messages Service Function
myApp.factory('DailyMsgService', function ($http) {
DailyMsgObj = {};
DailyMsgObj.DisplayDailyMsg = function () {
var Msg;
Msg = $http({method: 'GET', URL: '/DailyMsgs/Index'}).
then(function (response){
return response.data;
});
return Msg;
}
return DailyMsgObj;
});
myApp.controller('HomePageController', function ($scope, DailyMsgService) {
DailyMsgService.DisplayDailyMsg().then(function (result) {
$scope.DailyMsg = result;
});
});
My HomePage
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<div ng-controller="HomePageController">
{{DailyMsg}}
</div>
</body>
</html>
<script src="../Scripts/angular.min.js"></script>
<script src="../Scripts/bootstrap.min.js"></script>
<link href="../Content/bootstrap.min.css" rel="stylesheet" />
<script src="../AngularControllers/HomePageController.js"></script>
This is going to be a very generic question, so apologies in advanced. I have a python API call that I am trying to 'convert' to JS and HTML so I can create a dashboard with the data. What it does is display one numerical piece of data which we may assume is "500".
Here is my Python class which works perfectly:
url = 'https://someURL'
headers = {
"Authorization":"Bearer XXXX-XXXX",
"Content-Type":"application/json"
}
r = requests.get(url, headers=headers)
result = r.json()
print(result['Power'])
This returns a number from the API. Again, let's pretend it's "500". Now ere is my attempt at the JS: mainJS.js
var app = angular.module('tabletApp',[]);
app.controller('tabletCtrl',function($scope, $interval, $http){
var dataType = "json";
$scope.getData = function(){
var req = {
method: 'POST',
url: "https://XXXX",
headers: {
'Content-Type': 'application/json',
'Authorization':'Bearer XXXX',
data: postBody
};
$http(req).then(function(response) {
var data = response.data.result['consumptionPower'];
$scope.kw = response.data.result['consumptionPower'];
$scope.cost = calculateTouCost($scope.kw);
},
function(data) {
console.log(data);
});
}
$scope.getData();
$interval($scope.getData,10000);
});
And here is the supporting HTML to display the data in a webpage. index.html
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="mainJS.js"></script>
</head>
<body class="black" ng-app="tabletApp" ng-controller="tabletCtrl">
<div class="container center" class="black" >
<center><p><b><h1>ACTIVE WATTS FROM API: {{kw}}</h1></b><p></center>
</div>
</body>
</html>
So I've tried to make a script which would load the files needed for my AngularJS application.
But when I run the Angular.bootstrap part I get this error
Error description at AngularJS home page
This error is due to AngularJS not being able to find my masterController why is this. I've checked that the name of the module match, as well as the name of the controller and they do. So I'm very confused as to why I won't recognize the controller.
My code looks like this:
Index.html
<!doctype html>
<html ng-controller="masterController">
<head>
<!-- META -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1"><!-- Optimize mobile viewport -->
<meta name="author" content="Michael Tot Korsgaard">
<title>Mythodea map explorer</title>
<link rel="icon" type="image/png" href="favicon.png">
<script src="lib/JQuery/1.12.3/jquery.min.js"></script>
<script src="lib/AngularJS/1.5.5/angular.min.js"></script>
<script src="lib/AngularJS/1.5.5/angular-animate.min.js"></script>
<script src="lib/AngularJS/1.5.5/angular-aria.min.js"></script>
<script src="lib/UI-Router/0.2.18/ui-router.min.js"></script>
<script src="lib/moment/2.13.0/moment.js"></script>
<script src="js/log.js"></script>
<script src="js/build.js"></script>
</head>
<body ng-cloak>
<div ui-view></div>
</body>
</html>
core.js
var app = angular.module('AcademiaUnitate', [
'ui.router',
'ngAnimate'
]);
master.controller.js
angular.module('AcademiaUnitate')
.controller('masterController', function ($scope) {
});
build.js where my angular files are being added to my <head> tag
var buildStart = moment(),
fileCounter = 0;
initialize();
function initialize(){
loadJson('app')
.done(function(response){
var files = response.files,
folders = response.folders;
getFiles(files, 'app')
.done(function(response){
getFolders(folders, 'app')
.done(function(response){
bootstrap();
});
})
});
}
function getFolders(folders, path){
var deferred = $.Deferred();
if(folders.length > 0){
loadFolder(path + '/' + folders[0])
.done(function(response){
folders.splice(0, 1);
getFolders(folders, path)
.done(function(response){
deferred.resolve(response);
});
});
} else {
deferred.resolve(true);
}
return deferred.promise();
}
function getFiles(files, path){
var deferred = $.Deferred();
if(files.length > 0){
loadFile(path + '/' + files[0])
.done(function(response){
files.splice(0, 1);
getFiles(files, path)
.done(function(response){
deferred.resolve(response);
});
});
} else {
deferred.resolve(true);
}
return deferred.promise();
}
function loadFile(src){
var defer = $.Deferred(),
fileType = src.substring(src.lastIndexOf(".") + 1, src.length);
var head = $('head');
fileCounter++;
if(fileType.toLowerCase() === 'js'){
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = src;
document.getElementsByTagName('head')[0].appendChild(script);
defer.resolve(true);
} else {
defer.resolve(true);
}
return defer.promise();
}
function loadFolder(path){
var defer = $.Deferred();
loadJson(path)
.done(function(response){
var folders = response.folders,
files = response.files;
if(folders !== undefined){
getFolders(folders, path)
.done(function(response){
if(files !== undefined){
getFiles(files, path)
.done(function(response){
defer.resolve(response);
});
} else {
defer.resolve(response);
}
});
} else {
if(files !== undefined){
getFiles(files, path)
.done(function(response){
defer.resolve(response);
});
} else {
defer.resolve(response);
}
}
});
return defer.promise();
}
function loadJson(path){
var defer = $.Deferred();
$.get(path + '/structure.json', function(response) {
defer.resolve(response);
});
return defer.promise();
}
function bootstrap(){
$(document).ready(function(){
var bootstrapStart = moment();
angular.bootstrap(function(){
});
});
}
What my build.js file does is to find the file structure.json which tells which js files to add to the <head> tag and then which folders to look for additional structure.json files. When all that is done angular will be bootstrapped.
The file containing the masterController function is missing when Angular is bootstraping the application. Include the file. Help this help
You should probably consider naming your controller properly
angular.module('AcademiaUnitate')
.controller('MasterController', function MasterController($scope) {
});
Please see the controller documentation for the latest angular1 version at https://docs.angularjs.org/guide/controller and an example at https://docs.angularjs.org/tutorial/step_02
If all your angular code is in one file, you may want to do the following:
1) chain the controller after/ to the angular.module()
angular.module('AcademiaUnitate', [
'ui.router',
'ngAnimate'
]).controller('MasterController', function MasterController($scope) {
});
OR 2)use the app variable
var app = angular.module('AcademiaUnitate', [
'ui.router',
'ngAnimate'
]);
app.controller('MasterController', function MasterController($scope) {
});
You haven't included core.js in your index.html. That is why your controller is not found. Try including it.
<script src="core.js"></script>
you probably forget to add ng-app="AcademiaUnitate", just change <html ng-controller="masterController"> to <html ng-app="AcademiaUnitate" ng-controller="masterController">
I found the problem, it was the way I bootstrapped my application had to change
angular.bootstrap(function(){});
into
angular.bootstrap(document, ['AcademiaUnitate']);
I am creating a service to get the values saved as "FirstName" in a Row "name", when save is ok i have the values in the database, but when i try to get this values i have something like this:
people:
-
All the values in the list empty but i don't know why this happen if it is a problem in the controller or in the service.
<script src="https://www.parsecdn.com/js/parse-1.3.2.min.js"></script>
<div ng-app="app">
<ul ng-controller="MyCtrl">
people
<li ng-repeat="person in people">{{person}}</li>
</ul>
</div>
<script type="text/javascript">
Parse.initialize("key", "key");
var People = Parse.Object.extend("People");
var peoples= new People();
peoples.set("name", "FirstName");
peoples.save(null),{
success:function(peoples){
peoples.save();
}
}
var app = angular.module('app', []);
app.controller("MyCtrl", ["$scope", "PeopleService", function($scope, PeopleService){
$scope.people = PeopleService.getPeople();
}]);
app.service("PeopleService", function($q){
var people = null;
return {
getPeople: function(){
var deferred = $q.defer();
people = [];
var queryObject = new Parse.Query(People);
queryObject.find({
success: function (results) {
for (var i = 0; i < results.length; i++) {
var result = results[i];
people.push(result.get("name"));
}
deferred.resolve(people);
},
error: function (error) {
deferred.reject(error);
}
});
return deferred.promise;
}
}
});
</script>
You should set the $scope.people value from the success callback function of parse.com call.
Code
app.controller("MyCtrl", ["$scope", "PeopleService", function($scope, PeopleService){
PeopleService.getPeople().then(function(data){ //success fn
$scope.people = data
},function(data){ //error fn
$scope.people = data
});
}]);
I am trying to load some javascript dynamically using AngularJS promises.
HTML file (index.html)
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.4/angular.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.4/angular-route.js"></script>
<script type="text/javascript" src="main.js"></script>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
</head>
<body ng-app="main">
<ng-view></ng-view>
</body>
</html>
AngularJS file (main.js)
angular.module('main', ['ngRoute'])
.config(function($routeProvider) {
$routeProvider
.when('/',
{
controller: 'MainCtrl',
templateUrl: 'partial.html',
resolve: {
temp: MainCtrl.testFn
}
})
.otherwise({
redirectTo: '/'
})
})
MainCtrl = angular.module('main')
.controller('MainCtrl', function () {
});
angular.module('main')
.factory('MyFactory', function($q) {
data = {
loadJS: function() {
var deferred = $q.defer()
var script = document.createElement('script');
script.type = 'text/javascript'
script.src = 'https://apis.google.com/js/client.js'
script.onload = function() {
deferred.resolve('Google Client Library loaded')
}
document.body.appendChild(script)
return deferred.promise
}
}
return data
})
MainCtrl.testFn = function($log, MyFactory) {
return MyFactory.loadJS().then(function(result) {
$log.debug(result)
gapi.client.load()
})
}
The onload method is called (as the promise is resolved and debug line printed), but an error is being thrown because the client property is not found on gapi (Uncaught TypeError: Cannot read property 'load' of undefined).
What am I missing? Does anyone have a better way of dynamically loading JS with Angular promises (using only Angular and JS)?
I guess, the script is loading successfully but gapi.client is not available immediately. You need to provide handler to google api url on that purpose (some global function).
angular.module('app', [])
.controller('mainCtrl', function(googleClientLoader) {
googleClientLoader.load().then(
function() {
console.debug(gapi.client);
}
)
})
.factory('googleClientLoader', function($q) {
return {
load: function() {
var deferred = $q.defer()
var script = document.createElement('script');
script.type = 'text/javascript'
script.src = 'https://apis.google.com/js/client.js?onload=handleClientLoad';
window.handleClientLoad = function() {
deferred.resolve('Google Client Library loaded');
}
document.body.appendChild(script)
return deferred.promise;
}
}
})
Just load the content and use eval(data) to evaluate the Javascript.
a tag won't be processed as it is generated after the page loads.