constant not inject to config-angularjs - angularjs

I have a problem with angular-config to inject constant "ACCESS_LEVELS"?
Because when I like the code below, gets the message: Uncaught Error: [ng:areq] http://errors.angularjs.org/1.2.14/ng/areq?p0=fn&p1=not%20a%20function%2C%20got%20string
that is: Argument 'fn' is not a function, got string
if I delete the "ACCESS_LEVELS" with inject I do not have access route.
var app = angular.module("app", ["ngRoute", "ngAnimate"])
.constant('ACCESS_LEVELS', {
guest: 1,
user: 2,
admin: 3
});
app.config(["$routeProvider", "$locationProvider", "ACCESS_LEVELS", function($routeProvider, $locationProvider, ACCESS_LEVELS) {
$routeProvider
.when("/", {
template: "",
label: "Home",
access_level: ACCESS_LEVELS.user
})
.
.
.
}]);
maybe I made a simple mistake but I can not see it.
if anyone knows how to solve this problem please help.
regards

Make sure you are including angular-route.js and angular-animate.js file.
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular-route.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular-animate.min.js"></script>
DEMO

Related

angular route not working, throw page not found error

in index.html
<script src="lib/angular.min.js"></script>
<script src="lib/angular-route.min.js"></script>
controller
angular.module("testCtrl",[]).controller('TestController', ["$scope", function($scope) {
$scope.Myname = "my first route";
}]);
app.js
var app = angular.module('testApp',["ngRoute", "testCtrl"]);
app.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
$routeProvider
.when("/",{
templateUrl: "Views/main.html"
})
.when("/details",{
templateUrl: "Views/details.html",
controller : TestController
})
.otherwise({
redirectTo : "/"
});
}]);
my homepage loads fine but with some reason /details show error like --- No webpage was found for the web address: http://127.0.0.1:8080/details
I am new to angular and I am learning. I am not able to understand whats wrong ..do we have any tools to debug route error? I am using angular 1.5.8 version for now.
server console - "GET /details" Error (404): "Not found"
The issue is that TestController isn't defined in app.js. You should use the controller name as a string, like so.
.when("/details",{
templateUrl: "Views/details.html",
controller : "TestController"
})
See this plunk for a working example.
https://plnkr.co/edit/xi20MmchJY6TO1SG2o0d?p=preview
I think you have omitted the dependency on ngRoute:
angular.module('testCtrl', ['ngRoute'])...
Are you referencing ng-app in your HTML as well (can't see your HTML code)
Presumably you have included your scripts in the HTML page too?

How to load REST resources in Angular-Seed bootstrap project from a JEE7 back-end

I am trying to learn hot to invoke a RESTful service that I've implemented in JEE7. I am using the bootstrap template Angular-Seed and the file structure in the tutorial I am using looks a bit different. What I can't seam to figure out is how the $routeProvider and controller relate to each other.
The file structure I have look like this and is similar to the current Angular-Seed structure.
app/
bower_components/
components/
view1/
view1.html
view1.js
view1_test.js
view2/
view2.html
view2.js
view2_test.js
app.css
app.js
controller.js
service.js
index.html
index-async.html
Include the service and the controller in the index.html.
<script src="bower_components/angular-resource/angular-resource.js"></script>
<script src="services.js"></script>
<script src="controller.js"></script>
Added reference to the mainCtrl in app.js
'use strict';
// Declare app level module which depends on views, and components
angular.module('myApp', [
'ngRoute',
'myApp.view1',
'myApp.view2',
'myApp.version'
]).
config(['$routeProvider',
function ($routeProvider) {
$routeProvider.
when('/view1', {
templateUrl: 'view1/view1.html',
controller: 'mainCtrl'
})
}]);
In the services.js file I've declared the invocation of the RESTful service.
var tweetObsService = angular.module('tweetObsService', ['ngResource']);
tweetObsService.factory('tweetFactory', function($resource){
return $resource('http://localhost:8080/bongo-obs/rest/tweets/findAll', {}, {
query: {
method:'GET',
params: {},
isArray:true}
});
});
In the root file controller.js I've declared the mainCtrl.
angular.module('myApp')
.controller('mainCtrl', function($scope, tweetFactory) {
$scope.tweets = {};
tweetFactory.query().$promise.then(function(tweets) {
$scope.tweets = tweets;
});
});
The JSON that the service retrieves has the following structure.
[
{
"id": {
"timestamp": 1454579718,
"machineIdentifier": 12550416,
"processIdentifier": 6912,
"counter": 6510561,
"time": 1454579718000,
"date": 1454579718000,
"timeSecond": 1454579718
},
"userId": 0,
"status": null,
"user": {
"id": 291655833,
"name": "Anders Anderson",
"screenName": "Superuser",
"location": "Sweden",
...
Lats but not least, I tried to render result from the REST service in the view1/view1.html.
<table>
<tr ng-repeat="tweet in tweets">
<td>{{tweet.user.screenName}}</td>
</tr>
</table>
I've no alter the project thanks to submitted answer but I get an error related to the $injector
Error: [$injector:unpr] Unknown provider: tweetFactoryProvider <- tweetFactory <- mainCtrl
http://errors.angularjs.org/1.4.9/$injector/unpr?p0=tweetFactoryProvider%20%3C-%20tweetFactory%20%3C-%20mainCtrl
at http://localhost:8383/mobile-clear-obs/bower_components/angular/angular.js:68:12
at http://localhost:8383/mobile-clear-obs/bower_components/angular/angular.js:4346:19
at Object.getService [as get] (app/bower_components/angular/angular.js:4494:39)
at http://localhost:8383/mobile-clear-obs/bower_components/angular/angular.js:4351:45
at getService (app/bower_components/angular/angular.js:4494:39)
at invoke (app/bower_components/angular/angular.js:4526:13)
at Object.instantiate (app/bower_components/angular/angular.js:4543:27)
at http://localhost:8383/mobile-clear-obs/bower_components/angular/angular.js:9395:28
at link (app/bower_components/angular-route/angular-route.js:977:26)
at invokeLinkFn (app/bower_components/angular/angular.js:9039:9) (09:47:06:656 | error)
How do I correctly injection my mainCtrl, so I can use it in view1.html?
EDIT: Alter the question in response to the submitted.
2.
FINAL EDIT I finally got there with help from niklas. The last problem I stumbled upon is cross domain referencing, resulting in No 'Access-Control-Allow-Origin' header is present on the requested resource. If your backend is running on another server (still localhost), you have to allow cross domain calls to your back-end. Read this post how to solve this problem in JAX-RS 2.
The app.js
// Declare app level module which depends on views, and components
angular.module('myApp', [
'ngRoute',
'myApp.view1',
'myApp.view2',
'myApp.version',
'tweetObsService'
]).
config(['$routeProvider',
function ($routeProvider) {
$routeProvider.
when('/view1', {
templateUrl: 'view1/view1.html',
controller: 'mainCtrl'
})
}]);
The controllers.js
angular.module('myApp')
.controller('YourView1Controller', function($scope, tweetFactory) {
$scope.tweets = {};
tweetFactory.query().$promise.then(function(tweets) {
$scope.tweets = tweets;
}
}
For the view you can then access your desired data like
{{tweets.user.screenName}}and so on
To access the tweetFactory you have to declare the module tweetObsService. with the rest of the modules in myApp.
angular.module('myApp', [
'ngRoute',
'myApp.view1',
'myApp.view2',
'myApp.version',
'tweetObsService' //add this line
]). ...
Make sure your services.js is included in your index.html (some starter projects do it automatically...)

AngularJS controllers causing errors

I have a very simple application that does nothing really other than display two different views depending on user selection. This application is a stepping stone to learning how routes work in AngularJS.
My issue is this.
The application when run in the browser navigates to the index view with no issues. This is because the index view does not reference a controller. However the user view does reference (require) a controller. This causes an issue where the exception thrown is Arguement 'XCtrl' is not a function, got undefined.
My main index is:
<html>
<head><title></title></head>
<body>
<div ng-view></div>
</body>
</html>
My main app.js is:
angular.module('app.controllers', []);
var controllers = angular.module('app.controllers', []);
angular.module('app', ['app.controllers'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/', {
templateUrl: 'views/index.html'
})
$routeProvider.when('/users', {
templateUrl: 'views/users.html',
controller: 'UserCtrl'
}).
otherwise({ redirectTo: '/' });
}]);
My controller is:
appControllers.controller('UserCtrl', ['$scope', function ($scope) {
$scope.users = {
user: {name: "Ian", age: 30 },
user: {name: "Paul", age: 37 }
};
}]);
user.html
<div ng-repeat="user in users">{{user.name}} {{ user.age }}</div>
index.html
<h1>index</h1>
can anybody see where I am going wrong. Any help would be great
EDIT:
Here s the stack trace from the browser, if this helps any
Error: Argument 'UserCtrl' is not a function, got undefined
at Error ()
at bb (http://www.testapp.com/js/angular/angular.min.js:17:68)
at ra (http://www.testapp.com/js/angular/angular.min.js:17:176)
at http://www.testapp.com/js/angular/angular.min.js:53:60
at k (http://www.testapp.com/js/angular/angular.min.js:151:401)
at Object.e.$broadcast (http://www.testapp.com/js/angular/angular.min.js:90:517)
at http://www.testapp.com/js/angular/angular.min.js:83:6
at h (http://www.testapp.com/js/angular/angular.min.js:78:207)
at h (http://www.testapp.com/js/angular/angular.min.js:78:207)
at http://www.testapp.com/js/angular/angular.min.js:78:440
Also:
www.testapp.com is a locally hosted server with no external access, just in case someone tries it and can not access.
After see a related question I noticed that I had not added the UserCtrl.js to my main index.html. After adding this it worked. However, I believe there is a way to add controllers, directives, services and filters dynamically. If someone knows how to do this it would be very helpful.
Delete the brackets during assignments
angular.module('app.controllers', []);
var controllers = angular.module('app.controllers');
Or simpler do just htis:
var controllers = angular.module('app.controllers', []);
If you put the brackets you'll have two modules ...

Using JSON as a service in AngularJS

I realise there are a few answers to this question on here, but I just can't seem to get them working with my set up. This is a Plunker of what I am trying achieve (not my own work): http://plnkr.co/edit/Ofq7Md8udEnIhAPF1NgL?p=preview
Currently, I have this for my index.html file:
<body ng-app="HomeCourtArenaApp">
<div class="container" ng-view></div>
<script src="components/angular/angular.js"></script>
<script src="components/require/require.js"></script>
<script src="components/angular/angular-resource.js"></script>
<script src="scripts/services/data.js"></script>
<script src="scripts/app.js"></script>
</body>
To register the components, I have defined them in the karma.conf.js file:
files = [
JASMINE,
JASMINE_ADAPTER,
'app/components/angular/angular.js',
'app/components/angular/angular-resource.js',
'app/components/angular-mocks/angular-mocks.js',
'app/scripts/*.js',
'app/scripts/**/*.js',
'test/mock/**/*.js',
'test/spec/**/*.js'
];
To then create the service, I use the same technique that seems to be documented online in most examples:
'use strict';
angular.module('jsonData', ['ngResource'])
.factory('jsonData', function($resource) {
return $resource('data/shoe3Dconfig.js');
});
Where an error seems to be triggered is when I try to define the service in my 'app' variable, where adding the service name stops the content loading ['jsonData']:
'use strict';
var app = angular.module('HomeCourtArenaApp', ['jsonData']);
app.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/main.html',
controller: 'MainCtrl'
})
.otherwise({
redirectTo: '/'
});
});
I would share my views and controllers also, but before I can even use the JSON data in my template, there are an unearthly amount of errors to deal with:
Uncaught Error: Module name "path" has not been loaded yet for context: _. Use require([])
Uncaught Error: Mismatched anonymous define() module: function () {
return getStyleProperty;
}
Uncaught Error: No module: ngResource
There are some other errors also, but these seem to be mainly because the scripts further up the DOM are stopping them loading correctly. Any help would be great!
you could try this :
the app.js:
angular.module('HomeCourtArenaApp', ['HomeCourtArenaApp.services', 'HomeCourtArenaApp.controllers']).
config(['$routeProvider', ($routeProvider) {
$routeProvider.when('/', { templateUrl: 'views/main.html', controller: 'MainCtrl' });
$routeProvider.otherwise({ redirectTo: '/'});
}]);
angular.module('HomeCourtArenaApp.services', ['ngResource']).
factory('JsonData', function($resource){
return $resource('data/shoe3Dconfig.js');
});
angular.module('HomeCourtArenaApp.controllers', []).
controller('MainCtrl', ['$scope', 'JsonData', function($scope, JsonData) {
$scope.objs = JsonData.query();
console.log(objs);
}
}]);
and this is not necessary to load the datas in the html
<script src="scripts/services/data.js"></script>
This edited plunker http://plnkr.co/edit/33qW5VRnQVrHWFlp16kz?p=preview should get you further along the way.
You need to specify the module (jsonData) that you want in your app as a dependency. There is currently no name displayed since your data does not have a name property.
Your JSON service module definition named as 'jsonData'
angular.module('jsonData', ['ngResource'])
This module defines a service provider (factory) 'jsonService'
.factory('jsonService', function($resource) {
You list the 'jsonData' module as a dependency for your module so that you can access anything defined in there
var app = angular.module('plunker', ['jsonData']);
You then use Angular's Dependency Injection to request an instance of jsonService
app.controller('MainCtrl', function($scope, jsonService) {
Note that if you "production-ise" this and minify your JS, you will need to configure the DI code. I will leave that to you to find in the Angular docs.
Does this explain things a bit more?
And you can get the console in plunker by opening the developer tools in your browser.

angularjs ui-router: Unknown provider: $stateProvider

I'm having troubles using the ui-router plugin of AngularJS:
angular.module('myApp', []).
config(['$routeProvider', '$stateProvider', function($routeProvider, $stateProvider) {
$stateProvider
.state('mandats', {
url: '/domiciliations/mandats',
templateUrl: 'domiciliations/views/mandats.html',
controller: 'mandatsCtrl'
});
}])
I then get this error at startup:
Unknown provider: $stateProvider
I've included the javascripts in this order:
<script src="/Scripts/libs/angular/angular.js"></script>
<script src="/Scripts/libs/angular/angular-resource.js"></script>
<script src="/Scripts/libs/angular/angular-ui-states.js"></script>
What could be the issue ?
[EDIT]
I've got rid of the error message by adding 'ui.compat' as a dependency of myApp. I saw that in the sample code of ui-router but nowhere in the documentation. What is this about ?
Nevertheless, it still does not work. I've added ui-view to a div in the application index file. But the page remains blank.
The following piece of code should do the job. At least in my case, so let me know if it works or not.
angular.module('myApp', ['ui.compat']).
config(['$routeProvider', '$stateProvider', function($routeProvider, $stateProvider) {
$stateProvider
.state('mandats', {
url: '/domiciliations/mandats',
templateUrl: 'domiciliations/views/mandats.html',
controller: 'mandatsCtrl'
});
}])
Now about your issue with the page being empty. For sure the URL you have in the browser is not matched with any defined in your state. Try this '#/domiciliations/mandats' in your browser and see if the view gets rendered appropriately. Not that you absolute url should be something similar with http://[HOST_NAME]/home.html#/domiciliations/mandats.
You just need to include ui-router module as dependency.
like following
angular
.module('myApp', ["ui.router"])
.config(['$routeProvider', '$stateProvider', function($routeProvider, $stateProvider) {
...
}]);
Including the angular-ui v0.0.2 will fix the problem.

Resources