Load JSON file using AngularJS - javascript

I just started learning Angular and I've looked on SO for a solution to load a JSON file using angular and I've done what other people have posted a solutions but I cannot get the data from my json file to show for some reason.
my json file (test.json) is simple:
{
"array": [
{"thing": "thing1"},
{"thing": "thing2"},
{"thing": "thing3"}
],
"name": "robert"
}
this is my js file:
var myMod = angular.module("myMod", []);
myMod.controller("myCont", function ($scope, $http) {
$scope.thing = "hi";
$http.get("/test.json")
.success(function (data) {
$scope.stuff = data.array;
$scope.name = data.name;
})
.error(function (data) {
console.log("there was an error");
});
});
and i'm trying to just display the name like this but only {{name}} shows:
<html ng-app="myMod">
<head>
<script src="angular.js"></script>
<script src="testing.js"></script>
</head>
<body ng-controller="myCont">
{{stuff}}
</body>
</html>

I think you had typo, you should inject $http(responsible to make an ajax call) dependency instead of $html(doesn't exist in angular)
You should change code this way.
myMod.controller("myCont", function ($scope, $html) {
to
myMod.controller("myCont", function ($scope, $http) {

As Pankaj Parkar has stated, $http is what you need.
Here is a plunker I created with it working: http://plnkr.co/edit/d0DDU29uitMcwK6qA7kx?p=preview
app.js file with $http instead of $html:
var myMod = angular.module("myMod", []);
myMod.controller("myCont", function ($scope, $http) {
$scope.thing = "hi";
$http.get("test.json")
.success(function (data) {
$scope.stuff = data.array;
$scope.name = data.name;
})
.error(function (data) {
console.log("there was an error");
});
});

If anyone trying this is getting the error:
$http.get(…).success is not a function
Apparently the syntax changed for Angular >1.6. The accepted answer here has new syntax: $http.get(...).success is not a function

Related

Angularjs - Move service code to another file

I am having code like,
<script>
var MyApp = angular.module("MyApp", ['mc.resizer','chart.js'])
MyApp.controller('Ctrl1', function ($scope, $http,MyService) {
MyService.EnvDetails().then(function success(data){
$scope.httpdata = data;
}, function error(err){
console.log("error found"); return err;
});
});
</script>
And Trying to save service code in another javascript file in another folder which is like,
var MyApp = angular.module("MyApp", []);
MyApp.service('MyService', function($http) {
this.EnvDetails = function() {
return $http({
url: '/myurl'
}).then(
function successCallback(response) {
//Some Code
return //Some;
}, function errorCallback(response) {
return response;
}
);
};
});
Saving this code in "MyService.js" and referring this file in as
<script type="text/javascript" src="javascripts/MyService.js"></script>
This is giving me error,
angular.js:11607 Error: [$injector:unpr] Unknown provider:
getEnvDetailsServiceProvider <- getEnvDetailsService <- Ctrl1
But when i put Service code in same file (except the first line, var mainApp = angular.module("mainApp", []);) , along with controller code, it works. I am clueless, where i am missing the reference. Please help.
Thanks
When you are saving to another file, no need to add the modular declaration again,
remove the dependencies
//remove this line var MyApp = angular.module("MyApp", []);
MyApp.service('MyService', function($http) {
this.EnvDetails = function() {
return $http({
url: '/myurl'
}).then(
function successCallback(response) {
//Some Code
return //Some;
}, function errorCallback(response) {
return response;
}
);
};
});
var MyApp = angular.module("MyApp", []);
This line CREATES new module. You should invoke this only once.
In other files just use:
var MyApp = angular.module("MyApp");
To get currently existing module.

Use multiple service in same controller angular js

I want to use multiple service in same controller. I can achieve with different service as mentioned below but it performs only one service
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<H1>Random Text is:</H1>
<div>{{myRandom}}</div>
<p>MuyLocation:: {{myLocation}}.</p>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http, $location) {
$http.get("http://www.randomtext.me/api/").then(function (response) {
$scope.myRandom = response.data.text_out;
$scope.myLocation= $location.absUrl();
});
});
</script>
</body>
</html>
BUT, i want to use both service in same controller as mentioned below
app.controller('myCtrl', function($scope, $http, $location) {
$http.get("welcome.htm").then(function (response) {
$scope.myWelcome = response.data;
$scope.myUrl = $location.absUrl();
});
});
So How can we perform both services in same controller.
Thanks in advance.
I think you can solved your problem with promise chaining.
$http.get("http://www.randomtext.me/api/").then(function success(response) {
return $q.resolve(response);
}, function error() {
return $http.get("welcome.htm");
}).then(function success(response) {
$scope.myWelcome = response.data;
$scope.myUrl = $location.absUrl();
});
If call to randomapi failed, so fetch welcome.html.

How can I set Angular values from a config file?

I have an app that I have inherited that I have to support. So far it had only run on one server and we want to run it on different servers. We found hard coded references to the server name all over the place in python server code and C++ client code. It was easy enough to change those to read the server name from a config file. But now I find is a js module this code:
angular.module('app.config', []).constant('config', {"api":"http://foo.bar.com:8001/"});
How can I change this so that the value for the server is read dynamically from a config file or some other means that would not require it to be hard coded?
Here is an update with what I have tried:
Originally, my code had this:
angular.module('app.config', []).constant(
'config', {"api":"http://foo.bar.com:8001/"}
);
and I changed it to this:
angular.module('app.config').controller('myCtrl',
function($scope, $http) {
$http.get('./config.json')
.then(function(response) {
$scope.api = response.data;
});
});
and I got this:
error Module 'app.config' is not available!
Then I changed it to:
angular.module('app.config', [] ).controller('myCtrl',
function($scope, $http) {
$http.get('./config.json')
.then(function(response) {
$scope.api = response.data;
});
});
And then I get:
Error: [$injector:unpr] Unknown provider: configProvider <- config <- workitem
I feel I am very close, I just need a bit more help.
Another update:
I tried this:
angular.module('app').controller('home', ['$scope', homeCtrl]);
angular.module('app').controller('workitem', ['$scope', '$routeParams', '$sce', '$timeout', '$http', 'config', workitemCtrl]);
},{"./home/home.js":3,"./workitem/workitem.js":4,"angular":10,"angular-route":6,"angular-sanitize":8,"bootstrap-treeview/src/js/bootstrap-treeview.js":11}],2:[function(require,module,exports){
module.exports = function($scope,$http) {
$http.get('config.json').success(function(reponse) {
console.log("reponse --> "+reponse.api);
$scope.api = reponse.api;
});
}
But then of course app.config was not getting defined. How could I do this an still define app.config?
I just tried this:
var my_config = {};
$.getJSON("config.json", function(data) {
$.each(data, function(key, val) {
my_config[key] = val;
});
});
but I get my_config is not defined when I use it down in the controller. How can I make that variable available in the controller?
Try This
angular.module('app.config', [])
.constant('bbConfig',{
"api":"http://foo.bar.com:8001/"
});
In controller
angular.module('app.config', [])
.controller('MainCtrl',['$scope', 'bbConfig' , function ($scope, bbConfig){
console.log(bbConfig.api)
}]);
Create a service to read the config (json file) or make a call to server and store the response URL in LocalStorage like the following. You can access it from every where
$localStorage.api = response.Url ; // http://foo.bar.com:8001/
I was finally able to get this working by doing this up front:
angular.module('app').value('config', {
api: ''
});
angular.module('app').run(function($rootScope, $http, config) {
$http.get('config/config.json').then(function(response) {
config.api = response.data.api;
$rootScope.$broadcast('config-loaded');
});
});
Wrapping the main code in:
var init = function(){
}
And adding this at the end:
if (config.api) {
init()
} else {
var configLoaded = scope.$on('config-loaded', function() {
init();
configLoaded();
});
}
You can do:
Use ngConstant build task to wrap your standalone config file in JSON format into the includable angular.config data.
Suppose you have app/config.json file:
{
"myFirstCnt": true,
"mySecondCnt": { "hello": "world" }
}
Then after running the ngConstant task in you build you'll get dist/config.js (output) will be :
define(["require", "exports"], function(require, exports) {
return angular.module("my.module.config", ["ngAnimate"])
.constant("myFirstCnt", true)
.constant("mySecondCnt", { "hello": "world" })
.constant("myPropCnt", "hola!");
});
Gulp plugin, Grunt plugin, more on ngConstant
Use service to load the JSON file immediately after you app bootstraps in service or in the controller:
should avoid this:
app.controller('myCtrl',
function($scope, $http) {
$http.get('PATH_TO/config.json').then(function(response) {
$scope.myWelcome = response.data;
});
}
);
More on that way example here: Reading in JSON through Angular Resources Service
UPD 12-06
For parsing loaded JSON try this:
for (var name in data) {
if (data.hasOwnProperty(var)) {
my_config[var] = data[var];
}
}

HTML page doesn't see AngularJS module

I am entirely new to AngularJS. The task is however simple: to parse XML file from the url and make a table out of it.
Yet somehow angular doesn't load. I searched similar questions, but neither worked. My index.html:
<!doctype html>
<html ng-app="myApp">
<head>
<title>jj</title>
<script src="~/Scripts/angular.min.js"></script>
<script src="~/Scripts/angular.intellisense.js"></script>
<script src="~/Scripts/angular.js"></script>
<script src="~/Scripts/myscript.js"></script>
</head>
<body>
<div class="jumbotron">
<h1>ASP.NET</h1>
<p class="lead">Text.</p>
</div>
<div ng-controller="AppController">
<h3>for example 2+3= {{3+2}}</h3>
</div>
</div>
</body>
</html>
I should get 5 instead of 2+3 if angular is loaded?
myscript.js currently looks like:
angular.module('myApp.service', []).
myApp.factory('DataSource', ['$http', function ($http) {
return {
get: function(file,callback,transform){
$http.get(
file,
{transformResponse:transform}
).
success(function(data, status) {
console.log("Request succeeded");
callback(data);
}).
error(function(data, status) {
console.log("Request failed " + status);
});
}
}
}]);
angular.module('myApp', ['myApp.service']);
var AppController = function ($scope, DataSource) {
var SOURCE_FILE = "guitars.xml";
xmlTransform = function (data) {
console.log("transform data");
var x2js = new X2JS();
var json = x2js.xml_str2json(data);
return json.customers.customer;
};
setData = function (data) {
$scope.dataSet = data;
};
DataSource.get(SOURCE_FILE, setData, xmlTransform);
};
Can you give me some advice?
It has to do with your syntax. I believe you have 2 errors. In your myscript.js you are declaring 2 modules. In your first module you are incorrectly declaring a factory. Use .factory not myApp.factory
angular.module('myApp.service', [])
.factory('DataSource', ['$http', function ($http) {
return {
// do something
}
}]);
In your second module you declare a function called AppController instead of calling the .controller angular method. Do this instead:
angular.module('myApp', ['myApp.service'])
.controller('AppController', ['$scope', 'DataSource', function ($scope, DataSource) {
// controller code
}]);
You can accomplish your program in a sole module by using a construct similar to what follows:
var app = angular.module('myApp', []);
app.controller('AppController', function($scope, DataSource) {
// code
});
app.factory('DataSource', ['$http', function($http) {
// code
}]);
Basically, create a variable for your app module, then call controller and factory, and pass your factory into your controller.

Angular App works when all components are in one file, but throws 'nomod' error when components are in separate files

I'm working through this tutorial on creating a single-page MEAN stack todo app. I'm on this step, specifically. The tutorial covers modularization of code, and while I was able to separate my backend code (Express, Mongo, etc.) into modules successfully, when I separate my angular.js code, the todo app ceases to function. The specific error which is thrown to the console is "Uncaught Error: [$injector:modulerr]." The specific error is "nomod" (i.e. the module "simpleTodo" is failing to load.) I'd appreciate any help.
Code as one file (core.js):
var simpleTodo = angular.module('simpleTodo', []);
simpleTodo.controller('mainController', ['$scope', '$http', function($scope, $http) {
$scope.formData = {};
$http.get('/api/todos')
.success(function(data) {
$scope.todos = data;
})
.error(function(data) {
console.log('Error: ' + data);
});
$scope.createTodo = function() {
$http.post('/api/todos', $scope.formData)
.success(function(data) {
$scope.formData = {};
$scope.todos = data;
})
.error(function(data) {
console.log('Error: ' + data);
});
};
$scope.deleteTodo = function(id) {
$http.delete('/api/todos/' + id)
.success(function(data) {
$scope.todos = data;
})
.error(function(data) {
console.log('Error: ' + data);
});
};
}]);
Code in modules:
New core.js:
var simpleTodo = angular.module('simpleTodo',['todoController', 'todoService']);
Create/Delete Todo Service (todos.js):
angular.module('todoService', [])
.factory('Todos', ['$http', function($http) {
return {
get: function() {
return $http.get('/api/todos');
},
create: function(todoData) {
return $http.post('/api/todos', todoData);
},
delete: function(id) {
return $http.delete('/api/todos/' + id);
}
}
}]);
Controller file (main.js)
angular.module('todoController', [])
.controller('mainController', ['$scope', '$http', 'Todos', function($scope, $http, Todos) {
$scope.formData = {};
Todos.get()
.success(function(data) {
$scope.todos = data;
});
$scope.createTodo = function() {
if ($scope.formData !== null) {
Todos.create($scope.formData)
.success(function(data) {
$scope.formData = {};
$scope.todos = data;
});
}
};
$scope.deleteTodo = function(id) {
Todos.delete(id)
.success(function(data) {
$scope.todos = data;
});
};
}]);
Order of script loading on index.html:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.13/angular.min.js"></script>
<script src="js/controllers/main.js"></script>
<script src="js/services/todos.js"</script>
<script src="js/core.js"></script>
Thanks!
New info: After following floribon's advice, I get the same error, except instead of "simpleTodo" failing to load, it is "todoController" that cannot be loaded. I appreciate his advice but it still isn't working. :( Here's a github repo with his changes implemented, if you want to see: https://github.com/LeungEnterprises/simpleTodo
Since your controller needs to resolve the Todos dependency, you need to add the service todoService it to its module dependencies:
angular.module('todoController', ['todoService'])
Also, you will need to load the todos.js file before the main.js one (sicne it requires the former)
I perused my files and after extensive experimentation I deduced that the problem was being caused in the HTML file. The problem was an unclosed script tag.
However, I do appreciate everyone's help, especially #floribon!

Categories

Resources