I used to work with RequireJS and Backbone and used requirejs/text and requirejs-plugins to load local json files I normally use for configuration.
How does one achieve the same with AngularJS?
Everyone seems to suggest to use $http, but is this the only way?
Do I really need to make 20 calls if I have 20 configuration files?
Maybe something like ng-constant is the "preferred" way?
This is what I did. But it uses $http though so I'm hoping someone has a better solution.
app.js:
var myModule = angular.module('myApp', []);
myModule.config(function($routeProvider, $locationProvider) {
$routeProvider.when('/', {
templateUrl: 'html/home.html',
controller: 'MainCtrl as ctrl',
resolve: {
initializeData: function($q, $timeout, myService) {
return myService.promiseToHaveData();
}
}
});
});
myService.js:
var myModule = angular.module('myApp');
myModule.service('myService', function($http, $q) {
var _this = this;
this.promiseToHaveData = function() {
var defer = $q.defer();
$http.get('someFile.json')
.success(function(data) {
angular.extend(_this, data);
defer.resolve();
})
.error(function() {
defer.reject('could not find someFile.json');
});
return defer.promise;
}
});
Then I can inject myService anywhere and it will have all the fields from the json file.
I guess alternatively you could just make your .json files .js files, have them expose a global variable, and reference them in your index.html
Can you use jQuery's getJSON function?
E.g something like:
$.getJSON("config-1.json", function( data ) {
// do whatever you want
});
Here's an AngularJs service that uses the FileReader API:
http://odetocode.com/blogs/scott/archive/2013/07/03/building-a-filereader-service-for-angularjs-the-service.aspx
Related
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
I am writing a factory that calls a JSON feed and returns the results.
Here is the factory using $http
nearestLocationApp.factory("allTheLocationsFactory", function($http){
var locations = "Not sure why it don't work";
$http.get('/json/locations/').then(function(res){
locations = res.data;
});
return locations;
});
When I include this in the controller I get the first version of the locations variable. It's like there are 2 different scopes here. I am pretty sure that's my problem but I don't know why.
Here is me calling and printing out the console.log for the controller.
nearestLocationApp.controller("getTheLocation", function($scope, allTheLocationsFactory){
$scope.locationResponse = "Find your location";
$scope.locations = allTheLocationsFactory;
console.log($scope.locations);
});
What I need to know is why I have multiple scopes in my factory and how to fix it.
If anyone is interested the JSON data looks like this.
[
{
"Name":"#########",
"ID":#########,
"address1":"#########",
"address2":"#########",
"city":"#########",
"state":"#########",
"zip":"#########",
"phoneNumber":"#########",
"thumbnail":[
"#########",
#########,
#########,
#########
],
"permalink":"#########",
"weekdayHours":"#########",
"saturdayHours":"#########",
"sundayHours":"#########",
"coords":{
"longitude":"#########",
"latitude":"#########"
},
"options":{"animation":#########}
}, ......
You are dealing with asynchronous call, that gets data asynchronously for you. In this Your factory should return $http promise & you could get that promise inside your controller and put .then function, That will get call when the factory $http returns a locations from it success callback.
Factory
nearestLocationApp.factory("allTheLocationsFactory", function($http){
return $http.get('/json/locations/').then(function(res){
return res.data;
});
});
Controller
nearestLocationApp.controller("getTheLocation", function($scope, allTheLocationsFactory){
allTheLocationsFactory.then(function(data){
$scope.locations = data;
console.log($scope.locations);
})
});
Your factory instance should ideally return a promise instance that can be resolved either within a controller or ideally within a routers resolve option.
nearestLocationApp.factory("allTheLocationsFactory", function($http){
var jsonURL = '/json/locations/',
getLocations = function(){
return $http.get(jsonURL).then(function(result){
return result.data;
});
};
return {
getLocations: getLocations
};
});
Then within your application config or router something like;
var nearestLocationsApp = angular.module('myApp', [
'ngRoute'
])
.config(function($routeProvider) {
$routeProvider.when("/", {
templateUrl: "templates/someTemplate.html",
controller:'SomeCtrl',
controllerAs: 'ctrl',
resolve: {
locations: function(allTheLocationsFactory) {
return allTheLocationsFactory.getLocations();
}
}
});
});
And within your controller something similar to;
nearestLocationApp.controller('someController', [
'$scope',
'allTheLocationsFactory',
'locations',
function($scope, allTheLocationsFactory, locations) {
$scope.locations = locations;
}
]);
Or without using the resolve option in your router;
nearestLocationApp.controller('someController', [
'$scope',
'allTheLocationsFactory',
function($scope, allTheLocationsFactory) {
allTheLocationsFactory.getLocations().then(function(res) {
$scope.locations = res;
});
}
]);
The former option is one I personally prefer rather to relying on promises within the controller. You can check out some other useful angular tips here
Hope some of that helps you out!
i'm building application which uses CORS requests. Each request i use get host address from a constant
angular.module('siteApp').constant('baseUrl', {
'server':'htttp://localhost/',
})
And in each service i use to send request like this:
angular.module('siteApp').factory('DocsSvc', function ($http, baseUrl) {
var baseurl = baseUrl.server ;
$http.get(baseurl + 'document')
Is it possible to make 'htttp://localhost/' value - to came from config.json file into baseUrl constant or baseUrl factory?
I mean : how can i load something from ajax request an make it accessible to app modules
i have tried:
.run(['$rootScope', , function ($rootScope) {
$.ajax('config.json', {async: false})
.success(function (data) {
$rootScope.HOST = data.HOST;
});
And tried to access it from baseUrl:
angular.module('siteApp').factory('baseUrl',function($rootScope) {
return {
server: $rootScope.HOST
But no luck - the baseUrl.server comes undefined into functions
You can use run method of angular.
var app = angular.module('plunker', []);
app.run(function($http, $rootScope){
$http.get('config.json')
.success(function(data, status, headers, config) {
$rootScope.config = data;
$rootScope.$broadcast('config-loaded');
})
.error(function(data, status, headers, config) {
// log error
alert('error');
});
})
app.controller('MainCtrl', function($scope, $rootScope) {
$scope.$on('config-loaded', function(){
$scope.name = $rootScope.config.name;
});
});
see this plunker
If you want to do it even before the angular app starts, you can, instead of using the ng-app directive, use the bootstrap function.
From:
https://docs.angularjs.org/api/ng/function/angular.bootstrap
<!doctype html>
<html>
<body>
<div ng-controller="WelcomeController">
{{greeting}}
</div>
<script src="angular.js"></script>
<script>
var app = angular.module('demo', [])
.controller('WelcomeController', function($scope) {
$scope.greeting = 'Welcome!';
});
// Do your loading of JSON here
angular.bootstrap(document, ['demo']);
</script>
</body>
</html>
You need to tell angular about data change, so modify your code something like this:
.run(['$rootScope', function ($rootScope) {
$.ajax('config.json', {async: false})
.success(function (data) {
$rootScope.HOST = data.HOST;
$rootScope.$apply(); // New line
});
}])
That $apply() is needed since its a non-angular asynchronous call.
use the blow code snippet to load the json values
.run(function ($http, $rootScope) {
$http.get('launchSettings.json')
.success(function (data, status, headers, config) {
$rootScope.config = data;
$rootScope.$broadcast('config-loaded');
})
.error(function (data, status, headers, config) {
// log error
alert('error');
});
});
I have the following code to present data from a link (API) as suggestion for an autocomplete box. Although it is working for one link and not the other. I observed that data format for both are different, modified my code accordingly but it is still not helpful.
.js file:
var plunker= angular.module('plunker', ['ui.bootstrap', 'ngGrid']);
function TypeaheadCtrl($scope, $window, $http, limitToFilter) {
$scope.cities = function (cityName) {
return $http.jsonp("http://mtapi.azurewebsites.net/api/institute").then(function (response) {
return response[0].description;
});
};
}
HTML file:
<input type="text" id="depn" ng-model="formdata.department"
typeahead="suggestion.description for suggestion in cities($viewValue)"
placeholder="department" class="form-control">
If you replace the cities function with this one,
$scope.cities = function (cityName) {
return $http.jsonp("http://gd.geobytes.com/AutoCompleteCity?callback=JSON_CALLBACK &filter=US&q=" + cityName).then(function (response) {
return response.data;
});
};``
Even after I changed my code jsonP request to .get, it is still not working
var plunker= angular.module('plunker', ['ui.bootstrap', 'ngGrid']);
function TypeaheadCtrl($scope, $window, $http, limitToFilter) {
$scope.cities = function (cityName) {
return $http.get("http://mtapi.azurewebsites.net/api/institute").success(function(data) {
return data[0].description;
});
};
}
It is working fine.
Is there a problem with my code, or a back end server issue?
Change your cities function to use the data property of the response in your .then (that's how you'll access the response from a resolved HttpPromise):
var plunker= angular.module('plunker', ['ui.bootstrap', 'ngGrid']);
function TypeaheadCtrl($scope, $window, $http, limitToFilter) {
$scope.cities = function (cityName) {
return $http.get("http://mtapi.azurewebsites.net/api/institute").then(function (response) {
return response.data[0].description;
});
};
EDIT
Even making that code change won't solve your problem. This url does not support cross-origin requests, so you either need to host your angularjs app on the same domain and use a plain $http.get instead of $http.jsonp, or this url needs to support JSONP requests (the content-type of the response from this url is application/json. For JSONP to work it should be application/javascript).
I figured it out lately. Apart from the problem at back end there were issues in this code as well. I was returning the promise, but promise was never resolved to return the value also I was trying to return a string, whereas I should return array of strings. Here's the change:
$scope.aap = result.data;
var res = [];
res.push($scope.aap[0].Description);
return res;
Having trouble loading an external json file and having it's contents display on my view. I've included my view, controller and services code. What do I need to change?
view.html
<div ng-controller='BaseCtrl'>
<table class="table table-hover">
<tbody>
<tr class="tr-sep" ng-repeat="example in examples" ng-click="showUser(example)">
<td>{{example.name}}</td>
<td>{{example.type}}</td>
<td>{{example.size}}</td>
</tr>
</tbody>
</table>
</div>
controller.js
'use strict';
angular.module('projyApp')
.controller('BaseCtrl', function ($scope, data) {
$scope.examples = data.getAllExamples();
$scope.showUser = function(example) {
window.location = '#/user/' +example.size;
};
});
service.js
'use strict';
angular.module('projyApp')
.service('data', function data() {
var examples;
var getAllExamples = function () {
$http.get("../../TestData/Examples.json").success($scope.examples = data.examples);
};
});
Your service code isn't correct. I see the following problems:
You're creating a local variable getAllExamples that's not accessible from outside the service;
You're using the $http service, but that dependency isn't expressed in the service constructor;
You're trying to update the scope from the service, but it's inaccessible from there. Plus, the $scope variable is not even defined inside the service code.
Here's how your service could look like:
.service('data', function($http) {
this.getAllExamples = function(callback) {
$http.get("../../TestData/Examples.json")
.success(function(data) {
if (callback) callback(data.examples);
});
};
});
And your controller code would be like this:
.controller('BaseCtrl', function ($scope, data) {
data.getAllExamples(function(examples) {
$scope.examples = examples;
});
$scope.showUser = function(example) {
window.location = '#/user/' +example.size;
};
});
You could ditch the callback in the getAllExamples function and work directly with the $http.getreturned promise, but that's a bit more complicated.
Update Added a Plunker script to illustrate the code above.
Main module definition should look like:
angular.module("projyApp",[/*dependencies go here*/]);
Service should look like
//this use of module function retrieves the module
//Note from comments in angular doc: This documentation should warn that "angular.module('myModule', [])" always creates a new module, but "angular.module('myModule')" always retrieves an existing reference.)
angular.module('projyApp')
.service('dataService', [/*dependencies,*/function() {
var service = {
examples:[],
getAllExamples = function () {
$http.get("../../TestData/Examples.json").success(function(returnedData){examples = returnedData});
}
}
return service;
});
Controller should look like:
angular.module('projyApp')
.controller('BaseCtrl', function ($scope, dataService) {
$scope.examples = [];
$scope.showUser = function(example) {
window.location = '#/user/' +example.size;
};
$scope.$watch(function(){return dataService.examples}, function(newVal,oldVal) {$scope.examples = newVal});
});
Also you can add
debugger;
on an line to trigger Chrome to break (like a breakpoint but without having to dig through the scripts at run-time) so long as the Debugging Panel is open (F12)
You should use a callback instead of assigning in to a scope in you data service. By doing that, you can use this function in multiple controllers an assign values to appropriate scopes.
Data Service
var getAllExamples = function (callback) {
$http.get("../../TestData/Examples.json").success(function(data) {
if (typeof callback === "function") callback(data);
});
};
Controller
data.getAllExemples(function(data) {
$scope.examples = data;
});
EDIT
Another what is to create a promise object.
Data Service
var getAllExamples = function () {
return $http.get("../../TestData/Examples.json");
};
Controller
var promise = data.getAllExemples();
promise.then(function(data) {
$scope.examples = data;
});
EDIT 2
In your service, you need to return your functions
angular.module('projyApp')
.service('data', function data() {
var examples;
return {
getAllExamples: function () {
$http.get("../../TestData/Examples.json").success(...);
}
};
});
I want to do something like this (but obviously not this exactly, because this function doesn't work this way)
angular.bootstrap( $("#myelement"), ['myModule'], {foo: bar} );
I want to pass in a configuration object, since we may want to have more than one instance of the app on a page, with different settings, etc. All I can think of are ugly workarounds. I'm thinking the best thing would be to override an "Options" service of my own making, but I still can't figure out the proper way to do that (tersely).
Thanks in advance!
How about you try something like this:
angular.module('configFoo', []).run(function() {});
angular.module('configBar', []).run(function() {});
angular.bootstrap(myEl, ['myModule', 'configFoo']);
angular.bootstrap(myOtherEl, ['myModule', 'configBar']);
http://docs.angularjs.org/api/angular.Module for all available module methods (you're probably only interested in .run() and .config())
Here is a working code:
http://jsfiddle.net/x060aph7/
angular.module('myModule', [])
.controller('myController', function($scope,myConfig) {
$scope.name = 'inst '+myConfig.foo;
})
;
var aConfig = [{foo:1},{foo:2},{foo:3}];
aConfig.forEach(function(config){
angular.module('fooConfig',[]).value('myConfig', config);
angular.bootstrap(getDiv(), ['myModule','fooConfig']);
});
function getDiv(){
var mDiv = document.createElement('div');
mDiv.setAttribute('ng-controller','myController');
mDiv.innerHTML = '<span>{{name}}</span>';
document.body.appendChild(mDiv);
return mDiv;
}
The following example helped us out bootstrapping a widget to a page. First a div is made - with a bit of jQuery - for the widget to load a template with an ng-include, it is controlled by WidgetLogoController. Next a module WidgetConfig is created that holds the widget's configuration.
$('#pageWidget').html(`<ng-include src="'/dist/templates/widgetLogo.html'"></ng-include>`)
.attr('ng-controller','WidgetLogoController');
var widgetConfig = {
'widgetId': data.pageWidgetId,
'areaId': data.area,
'pageId': data.pageId
};
angular.module('WidgetConfig', []).value('WidgetConfig', widgetConfig);
angular.bootstrap(document.getElementById('pageWidget'), ['Widget', 'WidgetConfig']);
Widget module includes the WidgetConfig configuration but also has a spot for it own in CONFIG:
(function (window, angular) {
'use strict';
window.app = angular.module('Widget', ['ngFileUpload', 'WidgetConfig'])
.constant('CONFIG', {
BASE_URL: 'http://osage.brandportal.com/'
});
})(window, angular);
WidgetController can access CONFIG and WidgetConfig.
(function (app) {
'use strict';
app.controller('WidgetLogoController', ['CONFIG', 'WidgetConfig',
function(CONFIG, WidgetConfig){
console.log('---WidgetLogoController');
console.log('CONFIG', CONFIG);
console.log('WidgetConfig', WidgetConfig);
}]);
}(app));
What about:
Load config and than load angular:
angular.element(document).ready(() => {
$.get('config', // url to my configuration
{},
function (data) {
window.config = data;
angular.bootstrap(document, ['myApp']);
}
);
});
Access the config:
angular.module('myApp').run(myAppRun);
function myAppRun($window) {
$window.config; // here I have config
}