AngularJS error ng areq not a function - javascript

I'm trying to make my meta controller to dynamically change the meta tags, but in console i get error ng areq not a function. I searched through StackOverflow for similar problems but none of the solution is for my problem. I have these tags in my HTML:
<html ng-app="WebApp" >
<head ng-controller="MetaDataCtrl">
<meta name="description" content="{{ meta.tags.description }}">
</head>
<body >
<div ng-include='"templates/header.html"'></div>
<div ng-view></div>
</body>
</html>
Main.js
var app = angular.module('WebApp', [
'ngRoute'
]);
/**
* Configure the Routes
*/
app.config(['$routeProvider', '$locationProvider', function($routes, $location) {
$location.html5Mode(true).hashPrefix('!');
$routes
// Home
.when("/", {templateUrl: "partials/home.html",
controller: "PageCtrl",
metadata: {
title: 'This is my title',
description: 'This is Desc.' }
})
}]);
app.controller('PageCtrl', function (/* $scope, $location, $http */) {
});
.controller('MetadataCtrl', function ($scope, metadataService) {
$scope.meta = metadataService;
});

There is no such service metadataService and you don't defined it yourself. However, looks like you just need to accecc current route metadata object. In this case it's quite easy to do as it's part of the $route service. you should also set up a listener to update global meta object when route changes:
app.run(['$rootScope', function($rootScope) {
$rootScope.$on('$routeChangeSuccess', function(event, current) {
$rootScope.meta = current.metadata;
});
}]);
Demo: http://plnkr.co/edit/nQfqNWvoYQQElv909uZF?p=preview

Related

Does not show the view AngularJS

I try to show a view with angular paths. the console does not throw any error or warning.
But equally the view is not displayed.
What am I doing wrong?
index.html
<!DOCTYPE html>
<html lang="en" ng-app="app">
<head></head>
<body>
<ng-view></ng-view>
<!-- build:js bower/vendor -->
<script type="text/javascript" src="../bower_components/angular/angular.min.js"></script>
<script src="../bower_components/angular-route/angular-route.min.js"></script>
<!-- endbuild -->
<script src="./routes.js"></script>
<!-- build:app scripts/js || CUSTOMER -->
<script src="./components/customer/customerService.js"></script>
<script src="./components/customer/customerController.js"></script>
<!-- endbuild-->
</body>
</html>
routes.js
var _templateBase = './components';
angular.module('app', [
'ngRoute'
])
.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: _templateBase + '/customer/customer.html' ,
controller: 'customerController',
controllerAs: '_ctrl'
})
.otherwise({
redirectTo: '/'
});
}
]);
costomerService.js
angular.module('app', [])
.factory('customerService', function() {
});
costomerController.js
angular.module('app',[])
.controller('customerController', ['$scope', function($scope, customerService) {
//
}]);
It's wrong? Because the view is not displayed? I'm using obsolete mertodos, guide me lleguar many tutorials there.
Thanks so they can help.
This creates your app because you have included the second parameter (an array of dependencies to inject):
angular.module('app', [
'ngRoute'
])
Remove the second parameter on your other angular.module() definitions because that is causing a new app to be created each time.
angular.module('app') <-- no second parameter tells it to use the existing 'app' module
.factory('customerService', function() {
});
angular.module('app') <-- no second parameter tells it to use the existing 'app' module
.controller('customerController', ['$scope', 'customerService', function($scope, customerService) {
//
}]);
I added customerService to your injection array on your controller definition because the array elements have to match up exactly to your function parameters.
Also, if you are using controllerAs syntax as you have done on your route definition then you may not want to inject $scope into your controller.

Angular module error

i try to write an angular app using best code practice and i got to this:
index.html file contain :
<!DOCTYPE html>
<html ng-app='hrsApp'>
<head>
<title>Hrs app</title>
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body ng-controller="homeCtrl">
<div class='container'>
<div ng-view></div>
</div>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0/angular-route.min.js"></script>
<script src='app.js'></script>
<script src='js/controllers/homeCtrl.js'></script>
<script src='js/controllers/avCtrl.js'></script>
</body>
</html>
Main file: app.js:
angular.module('home', []);
angular.module('av', []);
// Declare app level module which depends on filters, and services
angular.module('hrsApp', [
'hrsApp.controllers',
'hrsApp.services',
'hrsApp.directives',
'hrsApp.filters',
// AngularJS
'ngRoute',
// All modules are being loaded here but EMPTY - they will be filled with controllers and functionality
'home',
'av'
]);
// configure our routes
angular.module('hrsApp').config([
'$routeProvider',
function ($routeProvider) {
'use strict';
$routeProvider
// route for the home page
.when('/', {
templateUrl: 'views/home.html',
controller: 'homeCtrl'
})
// route for the about page
.when('/av', {
templateUrl: 'views/av.html',
controller: 'avCtrl'
})
// route for the contact page
.otherwise({
redirectTo: '/'
});
}
]);
Then i added the home controller:
/*global angular*/
angular.module('home').controller('homeCtrl', [
'$scope',
function ($scope) {
'use strict';
$scope._init = function () {
$scope.message = "welcome to Home Ctrl";
};
// DESTRUCTOR
$scope.$on('$destroy', function () {
});
// Run constructor
$scope._init();
$scope.log('info', '[HomeCtrl] initialized');
}
]);
and home template that for the moment contain only a binding to the message variable:
<div>{{message}}</div>
When i try to run the application i got : Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.3.0/$injector/modulerr?p0=hrsApp&p1=Error%3A%…googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.3.0%2Fangular.min.js%3A18%3A3) angular.js:38
Any idea what i do wrong?
From your code I can see that you have injected modules that you did not declared.
in order todo so you must add the following lines to your code:
angular.module('hrsApp.controllers',[]);
angular.module('hrsApp.services',[]);
angular.module('hrsApp.directives',[]);
angular.module('hrsApp.filters',[]);

AngularJS Error: $injector:unpr Unknown Provider

I'm trying to build my own service by following the example in the documentation for the factory methodology. I think I've done something wrong however because I continue to get the unknown provider error. This is my code for my app including the declaration, configuration and factory definition.
EDIT
I've now added all of the files to help troubleshoot
EDIT
The full details of the error are below the issues appears to be with getSettings, as it's looking for getSettingsProvider and cannot find it
Error: [$injector:unpr] http://errors.angularjs.org/1.2.16/$injector/unpr? p0=getSettingsProvider%20%3C-%20getSettings
at Error (native)
at http://localhost/sw/selfservice/bower_components/angular/angular.min.js:6:450
at http://localhost/sw/selfservice/bower_components/angular/angular.min.js:35:431
at Object.c [as get] (http://localhost/sw/selfservice/bower_components/angular/angular.min.js:34:13)
at http://localhost/sw/selfservice/bower_components/angular/angular.min.js:35:499
at c (http://localhost/sw/selfservice/bower_components/angular/angular.min.js:34:13)
at d (http://localhost/sw/selfservice/bower_components/angular/angular.min.js:34:230)
at Object.instantiate (http://localhost/sw/selfservice/bower_components/angular/angular.min.js:34:394)
at http://localhost/sw/selfservice/bower_components/angular/angular.min.js:66:112
at http://localhost/sw/selfservice/bower_components/angular/angular.min.js:53:14 angular.js:9778
(anonymous function) angular.js:9778
(anonymous function) angular.js:7216
h.$apply angular.js:12512
(anonymous function) angular.js:1382
d angular.js:3869
$b.c angular.js:1380
$b angular.js:1394
Wc angular.js:1307
(anonymous function) angular.js:21459
a angular.js:2509
(anonymous function) angular.js:2780
q angular.js:330
c
These are all of the files I have in my app currently
app.JS
//Initialize angular module include route dependencies
var app = angular.module("selfservice", ['ngRoute']);
app.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl:"partials/login.html",
controller:"login"
});
});
app.factory('getSettings', ['$http', '$q', function($http, $q) {
return function (type) {
var q = $q.defer();
$http.get('models/settings.json').success(function (data) {
q.resolve(function() {
var settings = jQuery.parseJSON(data);
return settings[type];
});
});
return q.promise;
};
}]);
And here is how I am using this service in my controller
controller.JS
app.controller("globalControl", ['$scope','getSettings', function ($scope,getSettings) {
var loadSettings = getSettings('global');
loadSettings.then(function(val) {
$scope.settings = val;
});
}]);
app.controller("login", ['$scope', function ($scope) {
return ""
}]);
directives.js
app.directive('watchResize', function(){
return {
restrict: 'M',
link: function(scope, elem, attr) {
scope.spacer = (window.innerWidth < 1025) ? '' : 'large-3';
scope.button = (window.innerWidth < 1025) ? '' : 'large-6';
angular.element(window).on('resize', function(){
scope.$apply(function(){
scope.spacer = (window.innerWidth < 1025) ? '' : 'large-3';
scope.button = (window.innerWidth < 1025) ? '' : 'large-6';
});
});
}
};
});
And if it's pertinent here's the HTML
<html class="no-js" lang="en" ng-app="selfservice" ng-controller="globalControl">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>{{settings.title}}</title>
<link rel="stylesheet" href="css/app.css" />
<script src="bower_components/modernizr/modernizr.js"></script>
<script src="bower_components/angular/angular.min.js"></script>
<script src="bower_components/angular-route/angular-route.min.js"></script>
<script src="bower_components/jquery/dist/jquery.min.js"></script>
<script src="js/app.js"></script>
<script src="js/controllers.js"></script>
<script src="js/directives.js"></script>
</head>
<body>
<div id="template">
<header id="header">
<img src="{{settings.logo}}" alt="{{settings.logoDescription}}"/>
</header>
<div id="view">
<ng-view></ng-view>
</div>
</div>
<script src="bower_components/foundation/js/foundation.min.js"></script>
<script>
//initialize foundation
$(document).foundation();
</script>
</body>
</html>
Can someone point me in the right direction? I have done my best to follow the documentation, and looking through SO most of the related issues are much more in depth, and more difficult for me to understand. This is my first time creating a service.
also one of the popular reasons maybe you miss to include the service file in your page
<script src="myservice.js"></script>
Your angular module needs to be initialized properly. The global object app needs to be defined and initialized correctly to inject the service.
Please see below sample code for reference:
app.js
var app = angular.module('SampleApp',['ngRoute']); //You can inject the dependencies within the square bracket
app.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
templateUrl:"partials/login.html",
controller:"login"
});
$locationProvider
.html5Mode(true);
}]);
app.factory('getSettings', ['$http', '$q', function($http, $q) {
return {
//Code edited to create a function as when you require service it returns object by default so you can't return function directly. That's what understand...
getSetting: function (type) {
var q = $q.defer();
$http.get('models/settings.json').success(function (data) {
q.resolve(function() {
var settings = jQuery.parseJSON(data);
return settings[type];
});
});
return q.promise;
}
}
}]);
app.controller("globalControl", ['$scope','getSettings', function ($scope,getSettings) {
//Modified the function call for updated service
var loadSettings = getSettings.getSetting('global');
loadSettings.then(function(val) {
$scope.settings = val;
});
}]);
Sample HTML code should be like this:
<!DOCTYPE html>
<html>
<head lang="en">
<title>Sample Application</title>
</head>
<body ng-app="SampleApp" ng-controller="globalControl">
<div>
Your UI elements go here
</div>
<script src="app.js"></script>
</body>
</html>
Please note that the controller is not binding to an HTML tag but to the body tag. Also, please try to include your custom scripts at end of the HTML page as this is a standard practice to follow for performance reasons.
I hope this will solve your basic injection issue.
app.factory('getSettings', ['$http','$q' /*here!!!*/,function($http, $q) {
you need to declare ALL your dependencies OR none and you forgot to declare $q .
edit:
controller.js : login, dont return ""
This error is also appears when one accidntally injects $scope into theirs factory:
angular.module('m', [])
.factory('util', function ($scope) { // <-- this '$scope' gives 'Unknown provider' when one attempts to inject 'util'
// ...
});
Spent a few hours trying to solve the same. This is how I did it:
app.js:
var myApp = angular.module( 'myApp', ['ngRoute', 'ngResource', 'CustomServices'] );
CustomServices is a new module I created and placed in a separate file called services.js
_Layout.cshtml:
<script src="~/Scripts/app.js"></script>
<script src="~/Scripts/services/services.js"></script>
services.js:
var app = angular.module('CustomServices', []);
app.factory( 'GetPeopleList', ['$http', '$log','$q', function ( $http, $log, $q )
{
//Your code here
}
app.js
myApp.controller( 'mainController', ['$scope', '$http', '$route', '$routeParams', '$location', 'GetPeopleList', function ( $scope, $http, $route, $routeParams, $location, GetPeopleList )
You have to bind your service to your new module in the services.js file AND of course you have to use that new module in the creation of your main app module (app.js) AND also declare the use of the service in the controller you want to use it in.
I was getting this problem and it turned out I had included my controller both in ui.router and in the html template as in
.config(['$stateProvider',
function($stateProvider) {
$stateProvider.state('dashboard', {
url: '/dashboard',
templateUrl: 'dashboard/views/index.html',
controller: 'DashboardController'
});
}
]);
and
<section data-ng-controller="DashboardController">
Please "include" both Controller and the module(s) where the controller and the functions called in the Controller are.
module(theModule);
# user2310334
I just tried this, a VERY basic example:
HTML file
<!DOCTYPE html>
<html lang="en" ng-app="app">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.6/angular.min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.6/angular-route.min.js" type="text/javascript"></script>
<script src="./app.js" type="text/javascript"></script>
</head>
<body>
<div ng-controller="MailDetailCtrl">
</div>
</body>
</html>
The javascript file:
var myApp= angular.module('app', ['ngRoute']);
myApp.factory('mailService' , function () {
return {
getData : function(){
var employees = [{name: 'John Doe', id: '1'},
{name: 'Mary Homes', id: '2'},
{name: 'Chris Karl', id: '3'}
];
return employees;
}
};
});
myApp.controller('MailDetailCtrl',['$scope', 'mailService', function($scope, mailService) {
alert(mailService.getData()[0].name);
}]);
And it works. Try it.
Be sure that you load controller outsideapp.config. The following code may cause this error:
app.config(["$stateProvider", "$urlRouterProvider", function ($stateProvider, $urlRouterProvider) {
var AuthCtrl = require('components/auth/AuthCtrl'); //NOTICE HERE
$stateProvider.state('login',{
url: "/users/login",
templateUrl: require("components/auth/login.tpl.html"),
controller: AuthCtrl // ERROR
})
}))
To fix this error, we must move AuthCtrl to outsideapp.config:
var AuthCtrl = require('components/auth/AuthCtrl'); //NOTICE HERE
app.config(["$stateProvider", "$urlRouterProvider", function ($stateProvider, $urlRouterProvider) {
$stateProvider.state('login',{
url: "/users/login",
templateUrl: require("components/auth/login.tpl.html"),
controller: AuthCtrl // WORK
});
}))
In my case, I added a new service (file) to my app. That new service is injected in an existing controller. I did not miss new service dependency injection into that existing controller and did not declare my app module no more than one place. The same exception is thrown when I re-run my web app and my browser cache is not reset with a new service file codes. I simply refreshed my browser to get that new service file for browser cache, and the problem was gone.
Since this is the first Stackoverflow question that appears on Google when searching for Error: $injector:unpr Unknown Provider I'll add this here.
Make sure that in your index.html any modules/dependencies are not being loaded after they are needed.
For example in my code customFactory.factory.js begins like this:
angular
.module("app.module1")
.factory("customFactory", customFactory);
However the index.html looked like this:
<script src="/src/client/app/customFactory.factory.js"></script>
<script src="/src/client/app/module1.module.js"></script>
Where it should've really looked like this:
<script src="/src/client/app/module1.module.js"></script>
<script src="/src/client/app/customFactory.factory.js"></script>
Since customFactory.factory.js is declared as part of module1, it needs to be loaded before customFactory
I got this error writing a Jasmine unit test. I had the line:
angular.injector(['myModule'])
It needed to be:
angular.injector(['ng', 'myModule'])
When you are using ui-router, you should not use ng-controller anywhere. Your controllers are automatically instantiated for a ui-view when their appropriate states are activated.

How do I parse URL params after a hash with Angularjs?

I'm trying to parse for the access_token from Foursquare where the URL is like this:
https://mywebsite.com/4sqredirect/#access_token=1234567890XXXXX
I've tried $routeParams and $location and get nothing returned. Only after I tried $route, I did get an object back with the following attribute in it:
current: {
params: { }
pathParams: { }
loadedTemplateUrl: partials/4sqredirect
locals: { }
scope: {
this: {
$ref: $["current"]["scope"]
}
route: {
$ref: $
}
location: { }
token: null
}
}
Does this mean there's no way to get it using native AngularJS functions cause of the hash?
UPDATE:
my controller looks like as follows:
angular.module('myApp')
.controller('4sqredirectCtrl', function ($scope, $route, $location, $routeParams) {
$scope.route = $route;
$scope.location = $location;
$scope.token = $routeParams.access_token;
});
my main js looks like as follows:
angular.module('myApp', [
'ngCookies',
'ngResource',
'ngSanitize',
'ngRoute'
])
.config(function ($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$routeProvider
.when('/', {
templateUrl: 'partials/main',
controller: 'MainCtrl'
})
.when('/4sqredirect/', {
templateUrl: 'partials/4sqredirect',
controller: '4sqredirectCtrl'
})
.otherwise({
redirectTo: '/'
});
});
From angular location service $location.hash() method return #after-hash
so if your url is look like
https://mywebsite.com/4sqredirect/#access_token=1234567890XXXXX
then
$location.hash() return access_token=1234567890XXXXX
you need to split it split('=')[1]
see this plunker when you click 4Square then $location.url() return
/4sqredirect/#access_token=123456
$location.hash().split('=')[1]
return 123456
Use $location.search()
//e.g. url https://www.example.com/#!?name=123
var s = $location.search();
// {name: '123'}
http://docs.angularjs.org/api/ng.$location
Search:
Returns search part (as object) of current url when called without any parameter.
I'm not aware of a "native angular" way to do it, but you do have access to the hash via location.hash as a string type. it's probably not ideal, but it's workable.
There is in fact no direct support from Angular JS to do this. I wouldn't use ngRoute, because it already might expect the # at a different place. A simple solution to your problem is to use the location.hash and the substring() function:
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="http://code.angularjs.org/1.2.6/angular.js"></script>
<link href="style.css" rel="stylesheet" />
<script>
angular.module('app', [])
.controller('AppCtrl', ['$scope', '$window', function($scope, $window) {
$scope.accessToken = $window.location.hash.substring(14);
}]);
</script>
</head>
<body ng-controller="AppCtrl">
<h1>Access Token</h1>
<p>{{accessToken}}</p>
</body>
</html>

What's the best way to determine a route's template based on $cookies value in AngularJS?

I'd like the root URL, /, of my AngularJS app to display a template based on cookie value. For example, when a login cookie is present display dashboard. When login cookie is absent, display a login screen.
I tried to inject $cookies to app.config to determine the template property of $route based on it, but that didn't work.
var myApp = angular.module('myApp', ['ngRoute', 'ngCookies']);
myApp.config([
'$routeProvider',
'$locationProvider',
function ($routeProvider, $locationProvider) {
$routeProvider.
when('/', {
templateUrl: function() {
// read cookies here?
return '../../connect.html';
},
controller: "getAuthUrl"
});
$locationProvider.
html5Mode(true).
hashPrefix('!');
}
]);
Answering my own question...
After further investigation, I found out that $routeProvider is not what I should be using. $routeProvider is for serving templates based on URL routes. What this problem needed is the ui-router module, which is an official AngularJS module.
Instead of URLs, ui-router lets you specify page content based on "state". In my situation, I have a "loggedin" state and a "dashboard" state. Here's how I have implemented the solution:
var myApp = angular.module('myApp', ['ngCookies', 'ui.router']);
myApp.config([
'$stateProvider',
'$locationProvider',
function ($stateProvider, $locationProvider) {
$stateProvider.
state('login', {
template: '<h1>Login now.</h1>'
}).state('dashboard', {
template: '<h1>You are logged in. Welcome.</h1>'
});
$locationProvider.
html5Mode(true).
hashPrefix('!');
}
]);
myApp.controller('mainCtrl', [
'$scope',
'$state',
'$cookies',
function($scope, $state, $cookies) {
// You can read cookies here
if (true) {
console.log($cookies);
$state.go('dashboard');
}
else {
$state.go('login');
}
}
]);
And then the HTML is
<!DOCTYPE html>
<html ng-app='myApp'>
<head>
<script src='js/lib/angular.js'></script>
<script src='js/lib/angular-ui-router.js'></script>
<script src='js/lib/angular-cookies.js'></script>
<script src="js/app.js"></script>
</head>
<body ng-controller='mainCtrl'>
<div class="container" ui-view></div>
</body>
</html>
You can read all about ui-router in its wiki
Note: You have to use ui-router v0.0.2 at least. v0.0.1 won't work.

Categories

Resources