Locally Loading JSON Data into JavaScript File - javascript

I'm attempting to load a JSON file into my JavaScript file. However, I am at a loss at how to do so.
My app.js file:
var myApp = angular.module('myApp', []);
myApp.controller('MainCtrl', ['$scope', function ($scope) {
console.log("in here");
var jsonData = require('../test_data.json');
console.log(jsonData);
}]);
I have a test_data.json file in my project directory. The error above gives a "require is not defined", so it seems that I must install RequireJS? Is there another way to do so without installing any plugins?

Try using Angular's $http service and you'll have more control over the loading, errors, etc:
myApp.controller('MainCtrl', ['$scope', '$http', function ($scope, $http) {
console.log("in here");
$http.get('../test_data.json').success(function(data) {
console.log(data);
})
}]);

Related

Angular Selection Model injector error

I added the 'selectionModel' to my TestRateCtrl controller but I get an error:
angular.module('RDash', ['selectionModel'])
.controller('TestRateCtrl', function() {
I get this error:
Error: [$controller:ctrlreg] http://errors.angularjs.org/1.5.11/$controller/ctrlreg?p0=MasterCtrl
MasterCtrl is my master.js file. If I add 'selectionModel' to my master.js I get a different error.
angular.module('RDash', ['selectionModel'])
.controller('MasterCtrl', ['$rootScope', '$scope', 'configService', '$cookieStore', MasterCtrl]);
Now I get this error:
Error: [$injector:unpr] http://errors.angularjs.org/1.5.11/$injector/unpr?p0=%24cookieStoreProvider%20%3C-%20%24cookieStore%20%3C-%20MasterCtrl
I have the following in my index.html file:
src="components/angular-selection-model/dist/selection-model.js" charset="utf-8">
src="components/angular-selection-model/dist/selection-model.min.js" charset="utf-8">
By doing this would make two different scopes for your application becuase using same name of module if you reinitiallized that module that would be different that the other one which is already declared
say: file A
angular.module("RDash", ['selectionModel']);
This is defined and in file B
var app = angular.module("RDash", ['selectionModel']);
so this would cause to have two different app with same name in one application and that two app with same name in different files so its something like to have two different angular module inside on application.
so,
Replace this
angular.module('RDash', ['selectionModel']) .controller('TestRateCtrl', function() {
by
angular.module('RDash') .controller('TestRateCtrl', function() {
Same thing is happening here again
And here you are creating a MasterCtrl and adding MasterCtrl as dependencies
Replace this
angular.module('RDash', ['selectionModel']) .controller('MasterCtrl', ['$rootScope', '$scope', 'configService', '$cookieStore', MasterCtrl]);
by
angular.module('RDash') .controller('MasterCtrl', ['$rootScope', '$scope', 'configService', '$cookieStore']);
If anyone else is using the RDash framework (from startangular.com), and wants to use the angular-selection-model library, the way I was able to add the 'selectionModel' to the RDash framework is in the modules.js file as follows:
angular.module('RDash', ['ui.bootstrap', 'ui.router', 'ngCookies', 'selectionModel']);

How to fix Angular JS Error: [$injector:modulerr]

I am having a problem with Angular JS receiving an error
jquery.js:7993 Uncaught Error: [$injector:modulerr] Failed to instantiate module application due to:
Error: [$injector:nomod] Module 'application' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.
my controller is controller.js as follows
angular.module('application') .controller( 'controller', [ '$scope', 'service', '$uibModal', '$uibModalStack','$rootScope', function($scope, service, $uibModal, $uibModalStack,$rootScope) {}]);
and my service is service.js as follows
angular.module('application').service('service',
[ '$resource', function($resource) {
var requstService = $resource('test', {}, {
});
return requstService;
} ]);
when i load the view page it running perfectly but when i click again on site link it showing above error.Please help.
Your controller should be,
angular.module('siteApplication',[]) .controller( 'siteController', [ '$scope', 'siteService', '$uibModal', '$uibModalStack','$rootScope', function($scope, siteService, $uibModal, $uibModalStack,$rootScope) {
your module is missing []
your controller should be like:
angular.module('siteApplication',[])
also did you not paste the ending part of the controller i.e } ]);
on purpose ?
Use [] in your controller to create module like this.
angular.module('moduleName', [])
and use this in your html page like ng-app="moduleName"
and add dependency js file related to $uibModal.

'Unknown Provider' trying to Include angular-websocket in a MeanJS v0.4.1 app

I am having a bit of difficulty using angular-websocket in a controller in a MeanJS application I am working on.
My Application is based on MeanJS v0.4.1.
I first installed it with:
bower install angular-websocket --save
This created the directory /public/lib/angular-websocket
Next I added it to /config/assets/default.js
lib: {
css: [
...
],
js: [
...
'public/lib/angular-websocket/angular-websocket.js'
],
tests: ['public/lib/angular-mocks/angular-mocks.js']
},
In my /modules/core/client/app/config.js file I have added it as a dependency:
var applicationModuleVendorDependencies = [
...
'angular-websocket'
];
And finally in my angular module itself,
angular.module('somemodule').controller('ModulenameController', ['$scope', '$http', '$stateParams', '$location', 'Authentication', 'SomeModule', 'ngWebSocket',
function ($scope, $http, $stateParams, $location, Authentication, SomeModule, ngWebSocket) {
When I go to view my page I can see in the "Sources" tab of Chrome's Developer tools that it is included as a source,
I am trying to use this file with something like this in my controller:
var dataStream = ngWebSocket('wss://www.somesite.com/realtime');
dataStream.onMessage(function(message) {
console.log("dataStream Message: " + message);
$scope.orderBook = message;
});
dataStream.send('{"op":"subscribe", "args":"someargument"}');
However, my console shows the following error:
Error: [$injector:unpr] Unknown provider: ngWebSocketProvider <- ngWebSocket <- ModuleNameController
Some of the things I have tried:
Changing The Reference Name
As per the documentation (https://www.npmjs.com/package/angular-websocket)
angular.module('YOUR_APP', [
'ngWebSocket' // you may also use 'angular-websocket' if you prefer
])
I've tried using 'ngWebSocket', 'angular-websocket', but I still get the same issue.
I've tried looking through my code to see if maybe this was being redefined as the angularJS documentation here:
https://docs.angularjs.org/error/$injector/unpr
states that a cause of this error could be 'redefining a module using the angular.module API'.
Any help would be greatly appreciated.
The factory is actually named $websocket, so you should do as follows:
angular.module('somemodule').controller('ModulenameController', ['$scope', '$http', '$stateParams', '$location', 'Authentication', 'SomeModule', '$websocket',
function ($scope, $http, $stateParams, $location, Authentication, SomeModule, $websocket) {

Angular Js RouteProvider

I am using $routeProvider service in my angular js but problem is on templateURl it provides me error
from server here is the error what i received
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
angular.js:11594 Error: [$compile:tpload] Failed to load template: /Testing/TestCompleted
and here is my angular code for app.js
var app = angular.module('app', ['ngRoute']);
app.controller('CreateController', CreateController);
app.config(function ($routeProvider) {
$routeProvider
.when('/',
{
templateUrl: "/Testing/TestCompleted",
controller:"AppCtrl"
})
});
app.controller("AppCtrl",function ($scope) {
$scope.newmodel = {
}
});
I found the solution the view is only returned by server by using route we can only get html view not cshtml because that is provided when action is called.
The url is giving a ERROR 500. This is that there is something wrong in de code of the page. Please attach your debugger and go to the url "/Testing/TestCompleted" with a browser and check what is wrong.
Edit:
If the url is really the right one. Please try the following:
angular.module('app', ['ngRoute'])
.controller("AppCtrl",function ($scope) {
$scope.newmodel = {}
})
.config(function ($routeProvider) {
$routeProvider
.when('/',
{
templateUrl: "/Testing/TestCompleted",
controller:"AppCtrl"
})
});
So that the controller is registerd before you do your config as in the example from Angular (https://docs.angularjs.org/api/ngRoute/service/$route).
The address of the template is likely wrong. I never had to use a format such as '/....' .
You probably want 'Testing/TestCompleted' if the directory Testing is at the root of your project (or './Testing/TestCompleted' both should work).
EDIT:
In any case you are probably using an html file for the template, with an extension .html . So use 'Testing/TestCompleted.html' for instance.

AngularJS Jasmine Test Fails: Failed to instantiate module

My angular app worked great and so did my tests, using karma and jasmine, until I added a dependency in ui.bootstrap. Now the app still works as expected, but I can't get my tests to run. This is what I have:
app.js - added dependency in ui.bootstrap
angular.module('myApp', ['ngResource', 'ngRoute', 'ui.bootstrap']).config(function(...) {...});
service.js
angular.module('myApp').service('myService', function () {})
controller.js
angular.module('myApp').controller('MyController', function ($scope, $http, myService) {})
tests/main.js
describe('Controller: MyController', function () {
var MyController, scope;
// load the controller's module
beforeEach(function(){
module('myApp');
inject(function ($controller, $rootScope) {
scope = $rootScope.$new();
MyController = $controller('MyController', {
$scope:scope
});
});
});
it('should do something', function () {
expect(scope.myOptions.length).toBe(5);
});
});
And my test, which I run using grunt and krama, fails due to:
Error: [$injector:modulerr] Failed to instantiate module myApp due to:
Error: [$injector:modulerr] Failed to instantiate module ui.bootstrap due to:
Error: [$injector:nomod] Module 'ui.bootstrap' is not available! You either misspelled the module name or forgot
What have I missed? The app runs with no problem, only the test fails.
In karma.conf.js there is a list of files that karma loads before test execution:
// list of files / patterns to load in the browser
files: [
'bower_components/angular/angular.js',
'bower_components/angular-mocks/angular-mocks.js',
...
]
Add bootstrap-ui.js there.
Inject your dependencies
beforeEach(function(){
angular.module('ui.bootstrap',[]);
});
I had the same problem. Just solved it. Somehow putting the module(myApp); function call inside a the function you provide to beforeEach() doesn't work just try this:
Extract the module call into its own beforeEach():
beforeEach(module('myApp'));
And use another beforeEach() for the function you use.

Categories