I writing one constant file with Reff,
I getting the follwing Exception If I tried like that :
angular.min.js:118 Error: [$injector:unpr] http://errors.angularjs.org/1.5.8/$injector/unpr?p0=ENVProvider%20%3C-%20ENV%20%3C-%20viewRoleController
I get the error above in console:
My code as follows,
jsp:- included constant file location
angularController
var app = angular.module('App', ['angularUtils.directives.dirPagination','ui.bootstrap']);
app.controller('viewRoleController', function($scope, $http, ENV, viewRoleService) {
var dynamicData;
$http.get('js/commons/AngularConstantFile.js').then(function (response) {
dynamicData = response.data;
});
});
Constant file:-
var app = angular.module('App');
app.constant("ENV", {
"status412": "412",
"Success": "Success",
});
Just change your constant js file as follows, which will make sure to use the global instance of the module
angular.module('App').constant("ENV", {
"status412": "412",
"Success": "Success",
});
Try it like in this simple demo fiddle. Ensure your config is loaded after your main application into DOM and you will be fine.
AngularJS application
var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl', function ($scope, ENV) {
$scope.ENV = ENV;
})
myApp.constant("ENV", {
"status412": "412",
"Success": "Success",
});
An other approach is do create your config in an own module and parse it into your main application like in this demo fiddle. This will also work if your config is outsourced into an own file.
AnuglarJS application
var config = angular.module('config',[]).constant("ENV", {
"status412": "412",
"Success": "Success",
});
var myApp = angular.module('myApp', ['config']);
myApp.controller('MyCtrl', function ($scope, ENV) {
$scope.ENV = ENV;
});
Related
Hopefully this question doesn't get erroneously marked as a duplicate.
I am attempting to extend the AngularJS $routeProvider, as suggested as a response to a previous question. Unfortunately, this is not working, and I may have the syntax incorrect.
Here is a sanitized version of my "top-level" module:
// app.js
angular.module('app', ['ngRoute', 'ngSanitize'
, 'main'
])
.provider('appRoute', ['$routeProvider', function($routeProvider) {
this.$get = function($http) {
console.log("Instantiaing $rmaRouteProvider");
var universalResolves = {authorize: function($http) {
return $http.get('/svc/authorize/view?urlPath=' + path)
.then(function(response) {
var data = response.data;
if (response.data.result === 'NOT_AUTHORIZED') {
throw "NOT_AUTHORIZED";
}
console.log("finished authorized()");
return data;
});
}
};
var rmaRouteProvider = angular.extend({}, $routeProvider, {
when: function(path, route) {
route.resolve = (route.resolve) ? route.resolve : {};
angular.extend(route.resolve, universalResolves);
$routeProvider.when(path, route);
return this;
}
});
return rmaRouteProvider;
}
}]);
Here is my main.js, where I am attempting to define routes using the appRoute provider instead of the $routeProvider:
angular.module('admin', ['ngRoute', 'ngSanitize', 'ngCsv'])
.config(['appRouteProvider', function(appRouteProvider) {
appRouteProvider.when('/route', {
templateUrl: 'pageTemplate.tmpl.html',
controller: 'pageCtrl'
}
]);
Unfortunately, I get the following error:
Error: [$injector:modulerr] Failed to instantiate module app due to:
[$injector:modulerr] Failed to instantiate module main due to:
[$injector:unpr] Unknown provider: appRouteProvider
http://errors.angularjs.org/1.5.8/$injector/unpr?p0=%24appRouteProvider
minErr/<#https://localhost:8443/js/angular/angular.js:68:12
createInjector/providerCache.$injector<#https://localhost:8443/js/angular/angular.js:4511:19
getService#https://localhost:8443/js/angular/angular.js:4664:39
injectionArgs#https://localhost:8443/js/angular/angular.js:4688:58
invoke#https://localhost:8443/js/angular/angular.js:4710:18
runInvokeQueue#https://localhost:8443/js/angular/angular.js:4611:11
loadModules/<#https://localhost:8443/js/angular/angular.js:4620:11
forEach#https://localhost:8443/js/angular/angular.js:321:11
loadModules#https://localhost:8443/js/angular/angular.js:4601:5
loadModules/<#https://localhost:8443/js/angular/angular.js:4618:40
forEach#http…
As I said, I'm hoping this is an error with my syntax.
Edit: I realize that instatiation of providers is load-order specific. The app.js is the first <script> imported in the application index.html file and should be loaded first.
Edit 2: I have updated this question to the following: Custom Route Provider when is not a function
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];
}
}
i'm working with angular-seed project.
I'm trying to retreive data from mysql database.
I need to know how to define different controller for each view.
For example, I have this structure:
js
|_modules
|_companies
|_controller.js
|_data.js
|_app.js
|_base.js
I have added this route to app.js
.state('app.companies', {
url: '/companies',
title: 'Companies',
templateUrl: helper.basepath('companies.html'),
controller: 'companiesCtrl' //THIS THROWS THE ERROR BELOW
})
companies.html has scripts added to botom of the page
<script src="app/js/modules/companies/data.js"></script>
<script src="app/js/modules/companies/controller.js"></script>
and this is the code for controller.js (also tested the commented part)
(function() {
'use strict';
angular
.module('appname')
.controller('companiesCtrl', companiesCtrl);
companiesCtrl.$inject = ['$scope','companiesData','$log'];
function companiesCtrl($scope, companiesData, $log) {
console.log('asd'); //NEVER REACH THIS LOG
};
});
/*var app = angular
.module('appname')
.controller('companiesCtrl', ['$scope','companiesData','$log', function($scope, companiesData, $log){
console.log('asd'); //NEVER REACH THIS LOG
$scope.companies = {};
Data.get('companies').then(function(data){
$scope.companies = data.data;
console.log('($scope.companies)');
});
}]);
*/
But I keep getting
Error: [ng:areq] Argument 'companiesCtrl' is not a function, got undefined
Same if I script ng-controller="companiesCtrl" on my view.
change your function to:
(function() {
'use strict';
angular
.module('appname')
.controller('companiesCtrl', companiesCtrl);
companiesCtrl.$inject = ['$scope','companiesData','$log'];
function companiesCtrl($scope, companiesData, $log) {
console.log('asd'); //NEVER REACH THIS LOG
};
})();// execute this function then it will work
See this example if you remove () breaket then it will give you the error.
If possible then create controller like this:
angular.module('appname')
.controller('companiesCtrl', ['$scope', function($scope) {
console.log('asd'); //NEVER REACH THIS LOG
}]);
Please change your controller as :
(function() {
'use strict';
function companiesCtrl($scope, companiesData, $log) {
console.log('asd'); //NEVER REACH THIS LOG
};
angular
.module('appname')
.controller('companiesCtrl', companiesCtrl);
companiesCtrl.$inject = ['$scope','companiesData','$log'];
})();
The problem was on script loading.
I had to use lazy loading of the files within my app.js
Here's the code:
app.js companies route
.state('app.companies', {
url: '/companies',
title: 'Companies',
templateUrl: helper.basepath('companies.html'),
resolve: helper.resolveFor('companiesCtrl'),
controller: 'companiesCtrl'
})
lazy load code
.constant('APP_REQUIRES', {
scripts: {
'modernizr': ['vendor/modernizr/modernizr.custom.js'],
'icons': ['vendor/fontawesome/css/font-awesome.min.css',
'vendor/simple-line-icons/css/simple-line-icons.css'],
'companiesCtrl': ['app/js/modules/companies/data.js','app/js/modules/companies/controller.js']
},
modules: []
});
I want to add a new dependency, the 'angular-file-upload' dependency, but what ever I do, my app crashes, I can't understand how it works. What I've got now is:
in app.js
var myApp = angular.module('myApp', ['ui.bootstrap']);
in appController.js
myApp.controller('appCtrl', ['$scope', function ($scope) {
I've got all necessary resource files (angular-file-upload.js) and references to them, I just don't know how to properly inject the new dependency. I'm thinking I only need to edit the two provided lines, or do I have to create a whole new controller, and if so, what should that look like?
It says that my question is a possible duplicate of another, but on the other question it's about injecting dependencies into config() modules, this is not the case here.
Assuming you mean this project: https://github.com/danialfarid/ng-file-upload
then the snytax is like this:
var myApp = angular.module('myApp', ['ui.bootstrap', 'angularFileUpload']);
myApp.controller('appCtrl', ['$scope', 'FileUploader', function ($scope, FileUploader) {
}]);
The example below describes how to inject the stuff you would like to use. It is from here
//inject angular file upload directives and services.
var app = angular.module('fileUpload', ['ngFileUpload']);
app.controller('MyCtrl', ['$scope', 'Upload', function ($scope, Upload) {
^^^^^^^^ ^^^^^^
$scope.$watch('files', function () {
$scope.upload($scope.files);
});
$scope.upload = function (files) {
if (files && files.length) {
for (var i = 0; i < files.length; i++) {
var file = files[i];
Upload.upload({
url: 'upload/url',
fields: {'username': $scope.username},
file: file
}).progress(function (evt) {
var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
console.log('progress: ' + progressPercentage + '% ' + evt.config.file.name);
}).success(function (data, status, headers, config) {
console.log('file ' + config.file.name + 'uploaded. Response: ' + data);
}).error(function (data, status, headers, config) {
console.log('error status: ' + status);
})
}
}
};
}]);
Add the dependency to the Angular instance
var myApp = angular.module('myApp', ['ui.bootstrap', 'angularFileUpload']);
And add into your controller:
myApp.controller('appCtrl', ['$scope', 'FileUploader', function($scope, FileUploader) {
See the example on their Git page https://github.com/nervgh/angular-file-upload/blob/master/examples/simple/controllers.js
You need following ways.
If you have FileUploader.js file
track the files to your main html page after angular.js script before main.js(app.js)
Then configure it by this way
var myApp = angular.module('myApp', ['ui.bootstrap', 'fileUpload']);
myApp.controller('appCtrl', ['$scope', 'fileUpload', function ($scope, fileUpload) {
// Your code
}]);
If you have any doubt, please see this discussion :- Injecting Dependencies in config() modules - AngularJS
From the angular-file-upload wiki:
Add the dependency in your module declaration, these will be all the angular modules your application needs.
var myApp = angular.module('myApp', ['ui.bootstrap', 'angularFileUpload']);
To use its components in your controller you'll have also to inject FileUploader so you can access its API.
myApp.controller('appCtrl', ['$scope', 'FileUploader', function ($scope, FileUploader) {
You should write it like following:
var myApp = angular.module('myApp', ['ui.bootstrap', 'angular-file-upload']);
That's it. The dependence module should work fine.
You have to add the file to your angular.module:
var myApp = angular.module('myApp', ['ui.bootstrap', 'angular-file-upload']);
And import the file (for example in your index.html):
<script src="yourpath/ui-bootstrap-tpls.js"></script>
<script src="yourpath/angular-file-upload.js"></script>
If you correctly install your dependency, it should works :)
I want to load config file in Angular application, only the first time when application is opened. Then config variables become globally available across the application. Here is what I come up so far in my app.js:
angular
.module('myApp', [
...
])
.run(
[ '$rootScope', '$http',
function ($rootScope, $http) {
$http.get('config/config.json').success(function(data) {
$rootScope.config = data;
});
}
]
)
Here I load the config.js and when I try to use it in my controller like so:
angular.module('myApp')
.controller('MainCtrl', function ($rootScope) {
console.log($rootScope, $rootScope.config);
})
For $rootScope I can see all properties including config, but $rootScope.config returns undefined.
How to load config file on first page load and then make it accessible throughout the app?
Thanks!
As described in Mark Colemans blog post about this, you can get your config and then load the application. Pasting Mark's code for convenience:
var urlToCheck = '/echo/json/';
var myApp = angular.module('myApp', []);
myApp.controller("MyCtrl", ["$scope", "config", function ($scope, config) {
$scope.url = config.url;
}]);
$.ajax({
url: urlToCheck
}).fail(function () {
myApp.constant('config', {
url: '/fail-url'
});
}).done(function () {
myApp.constant('config', {
url: '/done-url'
});
}).always(function () {
angular.bootstrap(document, ['myApp']);
});
You can initialize it to a promise and then access it in the controller when the promise is resolve. reject the promise too.
http://plnkr.co/edit/EIBJhZg80lpeyhkMD3FD
$q.when($rootScope.config).then(function (config) {
console.log($rootScope.config, config);
});