AngularJS Unknow provider - javascript

I tried to set a new controller in my Angular app, but I have this error coming:
[$injector:unpr] http://errors.angularjs.org/1.4.2/$injector/unpr?p0=successRedirectProvider%20%3C-%20successRedirect%20%3C-%20ingreCtrl.
I tried many things for a few hours but still have this issue.
Here's my files:
app.js:
var app = angular.module('app', ['formSubmit']);
app.factory('successRedirect', function(){
return function(data) {
if(data.status === "success") {
alert(data.message);
if (typeof(data.redirect) !== "undefined"){
document.location.href = data.redirect;
}
}else{
}
};
});
app.factory('errors', function(){
return function(data) {
alert(data.message)
for(var i = 0; i<data.errors.length;i++){
$('#new-page-form-container').append('<p>'+data.errors[i]+'</p>');
}
};
});
formApp.js:
var formSubmit = angular.module('formSubmit', ['ckeditor', 'ngFileUpload']);
ingredientsCtrl.js:
formSubmit.controller('ingreCtrl', ['$scope', '$filter', '$http', 'successRedirect', 'errors', function ($scope, $filter, $http, successRedirect, errors) {
}]);

You're trying to use the successRedirect service of the app module inside your formSubmit module. That means you need to dependency inject app into formSubmit:
var formSubmit = angular.module('formSubmit', ['app', 'creditor', 'ngFileUpload']);
^^^^^
Not the other way around.

I finally found why it doesn't work, last week I did another module for the login system in my web site in another file, and I didn't remember that I already gave the name 'app' to this module, so I change my module's name in the file app.js and it works.
But to answer to some comments, my dependency injection was good, as my inclusion, no need to change the order. The problem was the module name.
Thanks anyway for your time, subject close ^^

Related

Require is not defined in AngularJS

I have two modules namely 'users' and 'groups', and have different routes in both of them. Now I want to use them in some other module, I am trying to require both the modules but getting error as required is not defined. How can I resolve it?
Here is my code:
appGroup.js
let myNinjaAppforGroup = angular.module('myNinjaAppforGroup',['ngRoute']);
//injected ngRoute module as a dependency in the above statement
myNinjaAppforGroup.config(['$routeProvider',function($routeProvider)
{
//code executes before application runs
$routeProvider
.when('/group/home',{
templateUrl:'views/home.html', //which view to be rendered if user visits this url
})
.when('/group/directory',{
templateUrl:'views/directory.html',
controller:'NinjaController'//it will be the controller for the mentioned route
}).otherwise({
redirectTo:'/group/home'
});
}]);
myNinjaAppforGroup.run(function()
{
//code executes when application runs
});
myNinjaAppforGroup.controller('NinjaController',['$scope','$http',function($scope,$http){
//scope is the glue between controller and view. Its also a dependency
$scope.message="Hey Angular!";//this is accessable in views
$scope.removeNinja = function(ninja)
{
let removedNinja = $scope.ninjas.indexOf(ninja);
$scope.ninjas.splice(removedNinja,1);
}
$scope.addNinja = function()
{
$scope.ninjas.push({
name:$scope.newNinja.name,
rate:parseInt($scope.newNinja.rate),
belt:$scope.newNinja.belt,
available:true
});
$scope.newNinja.name="";
$scope.newNinja.rate="";
$scope.newNinja.belt="";
}
$http.get('model/ninjas.json').then(function(response){
$scope.ninjas=response.data;
//console.log(response); for checking the object received
//whatever data we are getting from the http service is being saved here.
})
}]);
module.exports = myNinjaAppforGroup;
`and appUsers.js`
let myNinjaAppforUsers = angular.module('myNinjaAppforUsers',['ngRoute']);
//injected ngRoute module as a dependency in the above statement
myNinjaAppforUsers.config(['$routeProvider',function($routeProvider)
{
//code executes before application runs
$routeProvider
.when('/user/home',{
templateUrl:'views/home.html', //which view to be rendered if user visits this url
})
.when('/user/directory',{
templateUrl:'views/directory.html',
controller:'NinjaController'//it will be the controller for the mentioned route
}).otherwise({
redirectTo:'/user/home'
});
}]);
myNinjaAppforUsers.run(function()
{
//code executes when application runs
});
myNinjaAppforUsers.controller('NinjaController',['$scope','$http',function($scope,$http){
//scope is the glue between controller and view. Its also a dependency
$scope.message="Hey Angular!";//this is accessable in views
$scope.removeNinja = function(ninja)
{
let removedNinja = $scope.ninjas.indexOf(ninja);
$scope.ninjas.splice(removedNinja,1);
}
$scope.addNinja = function()
{
$scope.ninjas.push({
name:$scope.newNinja.name,
rate:parseInt($scope.newNinja.rate),
belt:$scope.newNinja.belt,
available:true
});
$scope.newNinja.name="";
$scope.newNinja.rate="";
$scope.newNinja.belt="";
}
$http.get('model/ninjas.json').then(function(response){
$scope.ninjas=response.data;
//console.log(response); for checking the object received
//whatever data we are getting from the http service is being saved here.
})
}]);
module.exports = myNinjaAppforUsers;
Now I have another file as app.js, I want to require these two files there, how can this be done?
Require doesn't work in browser.Basically require is a node_module by which we can access other modules or files.So please if you are using it on browser side then try other things like import or self.import or injecting.
Doc: http://requirejs.org/docs/download.html
Add this to your project: http://requirejs.org/docs/release/2.2.0/minified/require.js
and take a look at this http://requirejs.org/docs/api.html

Angular 1.5 component/require dependency injection of $log

I have been trying to inject $log in to a component created by a require statement for some client Angular.
var App = require('./app/containers/App');
var Header = require('./app/components/Header');
require('angular-ui-router');
var routesConfig = require('./routes');
import './index.css';
angular
.module('app', ['ui.router'])
.config(routesConfig)
.controller(App.App, ['$log'])
.service('todoService', todos.TodoService)
.component('app', App)
.component('headerComponent', Header);
The code for header is
module.exports = {
template: require('./Header.html'),
controller: Header,
bindings: {
todos: '='
}
};
/** #ngInject */
function Header(todoService) {
this.todoService = todoService;
}
Header.prototype = {
handleSave: function (text) {
if (text.length !== 0) {
this.todos = this.todoService.addTodo(text, this.todos);
}
}
};
~
The code for App is
module.exports = {
template: require('./App.html'),
controller: App
};
function App($log) {
this.log = $log;
$log.error('Hello from App');
}
I can inject $log as dependency for App as I have access to the controller. But attempting the same task for Header is difficult,because Header is created by require which does not seem to allow access to the controller function.
What I like to know is there a way round this?
I am trying to find a way of logging information from any possible javascript function in header.js.
I have seen any alternatives other than using $log to log information in a client side application
My solution so far has been to say in code written in the require block.
var ing = angular.injector(['ng']);
this.$log = ing.get('$log');
this.$log.error('I am a message');
I think this is the wrong way of doing things, it gives me what I want, but I expect it will break at some point. I find having access to $log is useful for debugging only. Its not sort of thing I need for any production code.
All I was trying to do was to get access to the $log angular wrapper. Turns out all I had to do was add $log to the argument list.
function Header(todoService,$log) {
$log.log('I am a log message');
this.todoService = todoService;
}
I am bit of a Angular 1.5 newbie and I had assume that you had to inject the $log to get the right response. Just declare it seems to be a bit of a kop out.

Loading a JSON into AngularJS Project Globally

The angular project I am working on is adding a configuration file to it. The configuration file is loaded as a JSON, it contains strings that will be replacing the static strings that are currently used in the current version of the project. There is multiple modules where the JSON's data needs to be used, what would be the best way to make the JSON file global throughout the project? I was thinking about loading it separately in each module using a HTTP GET, but I need the JSON to be loaded before everything else.
Thanks.
You probably can use a service. define a object on the scope and on that define the JSON. create a function which returns the JSON and inject it wherever the need arises. Implementation maybe like:
app.service("commonService", ["$log", function($log){
this.myConfiguration = {
id:"0",
name:"abc"
};
this.mystatic = function(){
return myConfiguration;
}
}
Now you can inject it and use in a controller as:
app.controller("mycontroller", function($scope, commonService){
$scope.static = commonService.myStatic();
//other code here
});
you can use value:
// create the module as usual
angular.module("myapp",[/*...*/]);
// on any other app point, set your json:
angular.module("myapp").value("myjson",{/*...*/});
If you don't need is before you do any routing you could use a service. This is what a config service could look like:
(untested)
app.service('ConfigService', function ($q, $http) {
// loads the config file
this.loadConfig: function() {
var deferred = $q.defer();
if(angular.isDefined(this.config) && this.config.length){
deferred.resolve(this.config);
}
$http.get('config.json')
.success(function(response) {
this.config = response;
deferred.resolve(this.config);
})
.error(function(){
deferred.reject('Could not load "config.json" file');
});
return deferred.promise;
};
// returns a config setting
this.get: function(key){
// if the config is not loaded yet, load it and call self
if(!angular.isDefined(this.config) || !this.config.length){
this.loadConfig().then(function(){
return this.get(key);
})
}
// config is loaded. Return requested key
if(angular.isDefined(config[key])){
return config[key];
}else{
console.error( 'Could not load config value: ' + key );
return false;
}
};
});

error with gulp-ng-annoate, couldn't process source due to parse error

I am getting trouble with error that is generated with gulp-ng-annoate.
Error message is
Error: app.js: error: couldn't process source due to parse error
I've found the other thread which seems to have same problem with me but that answer does not work for me.
the other thread
Here is my gulp file and the files that I am trying to execute the tasks.
gulpfile.js
var gulp = require('gulp')
var concat = require('gulp-concat')
//var uglify = require('gulp-uglify')
var ngAnnotate = require('gulp-ng-annotate')
gulp.task('js', function(){
gulp.src(['ng/module.js', 'ng/**/*.js'])
.pipe(concat('app.js'))
.pipe(ngAnnotate())
//.pipe(uglify())
.pipe(gulp.dest('assets'))
})
and files that I am trying to concat/ngAnnotate
module.js
angular.module('app', [])
posts.ctrl.js
angular.module('app')
.controller('PostCtrl', function($scope, PostsSvc){
$scope.addPost = function(){
if ($scope.postBody){
PostsSvc.create({
username: 'dickeyxxx',
body: $scope.postBody
}).success(function(post){
$scope.posts.unshift(post)
$scope.postBody = null
})
}
}
PostsSvc.fetch().success(function(posts){
$scope.posts = posts
})
})
posts.svc.js
angular.module('app')
.service('PostsSvc', ['$http', function ($http){
this.fetch = function(){
return $http.get('/api/posts')
}
this.create = function(post){
return $http.post('/api/posts', post)
}
}])
What could have gone wrong..?
What is wrong is that you put a . instead a , to separate object.
Also, don't forget the ; to end your line.

Angular throws an error when I have my service at a different file

I have a service like the folowing one:
var app = angular.module('app');
app.service('messagingService', function($http){
this.getMessages = function(offset, limit, successCallback, errorCallback){
// some stuff goes here
};
});
I include this file and afterwards I include my controller file.
My controller starts like this
function Inbox($scope, $http, messagingService) {
}
But when I load my page I get the following error:
Error: [$injector:unpr] http://errors.angularjs.org/undefined/$injector/unpr?p0=messagingServiceProvider%20%3C-%20messagingService
at Error ()
at https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js:6:453
at https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js:32:320
at Object.c [as get] (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js:29:461)
at https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js:32:388
at c (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js:29:461)
at d (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js:30:130)
at Object.Xb.instantiate (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js:31:284)
at $get (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js:61:304)
at https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js:48:476
When I use my service code in same file as the controller it works well. What am I missing here? Thanks
you need to attach your controller to your module.
var app = angular.module('app');
app.service('messagingService', function($http){
this.getMessages = function(offset, limit, successCallback, errorCallback){
// some stuff goes here
};
});
app.controller('Inbox',['$scope', '$http', 'messagingService',function($scope, $http, messagingService){}])
Good way is to inject the service as dependency for eg:
var app = angular.module('ur_app_name')
app.service('messagingService', function($http){
this.getMessages = function(offset, limit, successCallback, errorCallback){
//some stuff goes here
};
app.controller('GreetingController', ['$scope','messagingService' function($scope,messagingService) {
//something here
})
Try the following:
var app = angular.module('app', ['app.services']);
in your app.js
and then in your services.js
var services = angular.module('app.services');
services('messagingService', function($http){....

Categories