Pulled out all my hair on an Angular unpr error - angularjs

So I am getting an angular [$injector:unpr] error. Yes, I know what that normally means...I haven't defined something somewhere, or I am redefining the module over and over, or the like...but for the life of me I'm struggling to see the issue in my code.
I'm sure I'm missing something insanely basic, but after I've stared at code for a couple of hours, I go blind to it.
My HTML File:
<!DOCTYPE html>
<html ng-app="email">
<head>
<meta charset="UTF-8">
<title>Authentication</title>
<link href='https://fonts.googleapis.com/css?family=Roboto:400,100,300,500,700' rel='stylesheet' type='text/css'/>
<meta content="width=device-width, initial-scale=1.0" name="viewport">
</head>
<body>
<script src="bower_components/jquery/dist/jquery.min.js"></script>
<script type="text/javascript" src="node_modules/angular/angular.min.js"></script>
<div ng-controller="EmailAuthController as auth">
<h1>Authentication</h1>
<p>Request: [{{auth.request}}]</p>
<p>{{auth.response}}</p>
<p>{{1+2}}</p>
</div>
<script type="text/javascript" src="js/controllers/email.js"></script>
</body>
</html>
My email.js file (As you can see, I've commented out some stuff to try to isolate the issue):
/* global angular parseGet */
function parseGet(val) {
var result = '', // = "Not found",
tmp = [];
var items = location.search.substr(1).split('&');
for (var index = 0; index < items.length; index++) {
tmp = items[index].split('=');
if (tmp[0] === val) {
result = decodeURIComponent(tmp[1]);
}
}
return result;
}
(function () {
angular
.module('email', [])
.controller('EmailAuthController', [ '$scope','authFactory', function ($scope,authFactory) {
var vm = this,
req = parseGet('hash') || '';
vm.request = req;
// authFactory.validate(req)
// .then(function (response) {
// vm.response = response.data;
// });
}])
.factory('authFactory', [ '$rootScope', '$http', 'config', function ($rootScope, $http, config) {
var validate = function (hash) {
var url = config.SERVICE_URI + '/auth/email/' + hash;
return $http.get(url);
};
return {
validate: validate
};
}]);
})();

From the code you've given it appears config is not defined in your authFactory injection.
.factory('authFactory', [ '$rootScope', '$http', 'config', function(a, b, c) {} ]); // config is not defined

Related

$http get shortcut messing up program in AngularJS?

In the script below, I have posted a boiled down version of my code. It's essentially a simplified search engine.
The script loops through the $scope.list_of_fruit array, and filters it according to what is typed on a simple html input text box.
<script>
var app = angular.module("myapp",[]);
app.controller("usercontroller", function($scope){
$http
.get("test.php")
.then(function (response) {
$scope.myData = response.data.records;
});
$scope.list_of_fruit = ["apple", "banana", "pear", "kiwi"];
$scope.complete = function(boxtext){
var output = [];
angular.forEach($scope.list_of_fruit, function(fruit){
if(fruit.toLowerCase().indexOf(boxtext.toLowerCase()) == 0)
{
output.push(fruit);
}
});
$scope.filteredfruit = output;
}
});
</script>
This works fine and dandy, but when I paste that http get request up top, that is completely unrelated to that $scope.complete loop, the $scope.complete loop just stops working.
Am I missing something obvious?
app.controller("usercontroller", function($scope){
You don't have $http defined, so you are probably getting an javascript error.
Add $http to the function parameters:
app.controller("usercontroller", function($scope, $http){
I created a snippet and this appears to work now
var app = angular.module('myApp', []);
app.controller("usercontroller", function($scope, $http){
$http
.get("https://jsonplaceholder.typicode.com/posts")
.then(function (response) {
$scope.myData = response.data.records;
});
$scope.list_of_fruit = ["apple", "banana", "pear", "kiwi"];
$scope.complete = function(boxtext){
console.log(boxtext);
var output = [];
angular.forEach($scope.list_of_fruit, function(fruit){
if(fruit.toLowerCase().indexOf(boxtext.toLowerCase()) == 0)
{
output.push(fruit);
}
});
$scope.filteredfruit = output;
}
});
<!DOCTYPE html>
<html ng-app='myApp'>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<script src="https://rawgit.com/angular/bower-angular/master/angular.min.js"></script>
<div ng-controller="usercontroller as vm">
{{list_of_fruit}}
{{filteredfruit}}
<input type="text" ng-model="search"/>
<button ng-click="complete(search)">Do something</button>
</div>
</body>
</html>

Angular Storing array into Cookie

I have a function below that works fine and passes info into and retrieves from a cookieStore without issue
$scope.num = 0
$scope.nums = []
$scope.increment = function () {
$scope.num++
}
$scope.$watch('num', function () {
$scope.nums.push($scope.num)
})
$scope.storeProductsInCookie=function(){
$cookieStore.put("invoices",$scope.nums)
};
$scope.getProductsInCookie=function(){
console.log( $cookieStore.get("invoices",$scope.nums));
}
However when I try with the below verufyGuess function that is injecting the Index and no as parameters into the function it fails to place into the cookieStore
$scope.verifyGuess = function (Index , no) {
$scope.votes = {};
$scope.newVotes = []
$scope.votes[Index] = $scope.votes[Index] || 0;
$scope.votes[Index]+= no;
$scope.$watch('votes', function () {
$scope.newVotes.push($scope.votes)
})
$scope.storeProductsInCookie=function(){
$cookieStore.put("invoices",$scope.newVotes)
};
$scope.getProductsInCookie=function(){
console.log( $cookieStore.get("invoices",$scope.newVotes));
}
$cookieStore is Deprecated: (since v1.4.0)
Please use the $cookies service instead.
$scope.nums is an array of strings.So $cookieStore is storing them as string(cookies only support strings to store).
In second case $scope.newVotes is an array of objects. cookies wont store objects.
you must use $cookieStore.put("invoices", JSON.stringify($scope.newVotes))
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<script>
document.write('<base href="' + document.location + '" />');
</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js#1.4.x" src="https://code.angularjs.org/1.4.12/angular.js" data-semver="1.4.9"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.12/angular-cookies.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<script>
var app = angular.module('plunker', ['ngCookies']);
app.controller('MainCtrl', function($scope, $cookies) {
$scope.votes = {};
$scope.newVotes = []
var Index = 0;
$scope.votes[Index] = $scope.votes[Index] || 0;
$scope.votes[Index] += 10;
$scope.newVotes.push($scope.votes)
$scope.storeProductsInCookie = function() {
$cookies.put("invoices", JSON.stringify($scope.newVotes))
};
$scope.getProductsInCookie = function() {
console.log($cookies.get("invoices"));
}
$scope.storeProductsInCookie();
$scope.getProductsInCookie();
});
</script>
</body>
</html>

AngularJs dependency injection related to $http

While writing the above code in AngularJs, I am getting an error :
Error: $injector:unpr
Unknown Provider
Unknown provider: $http
I believe the reason might be while injecting $http through the serviceProvider which in my case is httpServiceProviderFunction.$inject = ["$http"];. I would appreciate if anyone could help me understand these two questions:
1) Although I have injected the $http in the httpServiceProviderFunction. Why am I getting the above error?
2)Is there any way I can inject $http in the service directly without injecting in serviceProvider? In my example, it corresponds to this line:
function httpService(url, $http) {.....}
The code snippet can be found below:
(function() {
angular.module("httpServiceApp", []).controller("httpServiceController", httpServiceControllerFunction).provider("httpService", httpServiceProviderFunction).config(configObj);
configObj.$inject = ["httpServiceProvider"]
function configObj(httpServiceProvider) {
httpServiceProvider.configuration.baseUrl = "http://davids-restaurant.herokuapp.com/categories.json";
}
httpServiceProviderFunction.$inject = ["$http"];
function httpServiceProviderFunction($http) {
var provider = this;
provider.configuration = {
baseUrl: "http://davids-restaurant.herokuapp.com/categories.json"
}
provider.$get = function() {
var service = new httpService(provider.configuration.baseUrl, $http);
return service;
}
}
function httpService(url, $http) {
var service = this;
service.menuCategories = function() {
var response = $http({
method: "GET",
url: url
});
return response;
}
}
httpServiceControllerFunction.$inject = ["httpService"]
function httpServiceControllerFunction(httpService) {
var service = httpService;
var controller = this;
var promise = service.menuCategories();
promise.then(function(response) {
controller.categories = response.data;
}).catch(function(error) {
console.log("Error occured", error);
})
}
})();
<!DOCTYPE html>
<html ng-app="httpServiceApp">
<head>
<meta charset="utf-8">
<meta name="description" content="First Angular App">
<meta name="keywords" content="HTML, Javascript, AngularJs">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://code.angularjs.org/1.6.1/angular.min.js"></script>
<script src="app1.js"></script>
<title>HTTP service in AngularJs</title>
</head>
<body>
<div ng-controller="httpServiceController as controller">
<div>
<ul>
<li ng-repeat="items in controller.categories">({{items.short_name}}){{items.name}}</li>
</ul>
</div>
</div>
</body>
</html>
Thank you for your time. I appreciate your help.

Syntax to access rootScope variable in MyController

In the below code,
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.20/angular.js"></script>
<script type="text/javascript">
function MyController() {
this.Name = "jag";
this.sal = "4500";
}
MyController.prototype.getAnnualSal = function(){
return (this.sal) * 12;
}
var app = angular.module("sample", []).run(function($rootScope) {
$rootScope.variable = 1;
});
app.controller("emp", MyController);
</script>
</head>
<body ng-app="sample">
<div ng-controller="emp as o" >
Hello {{o.Name}}, your annual salary is {{o.getAnnualSal()}}
</div>
</body>
</html>
Using run syntax, $rootScope.variable is introduced at module(sample) level.
What is the syntax to access $rootScope.variable in MyController?
Inject rootScope in controller like this.
angular.module('sample', []).controller('emp', function($scope, $rootScope) {
};
Aside from your issue I dont know why you are mixing controller code in view.Angular is built on MVVM pattern.So separation of controller and view is recommended.
You could do the following, inject $rootScope into the controller
<script type="text/javascript">
function MyController($rootScope) {
this.Name = "jag";
this.sal = "4500";
}
MyController.prototype.getAnnualSal = function(){
return (this.sal) * 12;
}
var app = angular.module("sample", []).run(function($rootScope) {
$rootScope.variable = 1;
});
MyController.$inject = ['$rootScope'];
app.controller("emp", MyController);
</script>

Angular skip the get method calling web service

var l = $scope.PendingKOTitems.length,
k = 0;
for (k = 0; k < l; k = k + 1) {
sItemCode = $scope.PendingKOTitems[k]["sItemCode"]
sOutletCode = $scope.selectedOutlet.sOutletCode;
sFinal = sOutletCode + "/" + sSubCatgCode
$http.get(sServiceURL + 'ItemMst/' + sFinal).then(function (resp) {
$scope.Items = resp.data;
iindexItem = getIndexOf($scope.Items, sItemCode, "sItemCode");
}, function (err) {
console.error('ERR', err);
// err.status will contain the status code
})
sCheckValue = $scope.CheckboxSelection.value;
$scope.invoice.items.push({
KOTNo: $scope.KOTNumValue,
ActiveMode: $scope.lActiveMode,
SubCatgCode: sSubCatgCode,
SubCatgDesc: sSubCatgDesc,
indexSubCatg: iindexSubCatg,
ItemCode: sItemCode,
ItemDesc: sItemDesc,
indexItem: iindexItem,
Qty: sQty,
OutletCode: sOutletCode,
BillType: sBillType,
MemberCode: sMemberCode,
RoomNum: sRoomNum,
BookingCode: dBookingCode,
TableCode: sTableCode,
WaiterCode: sWaiterCode,
UserID: sUserID
});
}
The get methode not fire in the for loop, after perform for loop it will fire.
I want get 'iindexItem' value for load select based on item sub category. But get method fire after the 'push' operation perform. so i was not able to get 'iindexItem' value. this my problem.
I tried this and this seems to work fine for me --
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.1/angular.js"></script>
</head>
<body ng-app="app">
<div ng-controller="ctrl">
<h1>This is a Heading</h1>
<p>This is a paragraph.</p>
</div>
<script type="text/javascript">
var angularapp = angular.module("app",[]);
angularapp.controller('ctrl', ['$scope', '$window', '$http', '$filter', '$timeout', MyCtrl]);
function MyCtrl($scope, $window, $http, $filter, $timeout){
for(var i=0; i<3; i++){
$http.get("http://httpbin.org/get").then(function (resp) {
debugger;
$scope.Items = resp.data; // here I set my breakpoint
console.log(i);
console.log(resp.data);
}, function (err) {
console.error('ERR', err);
// err.status will contain the status code
});
}
}
</script>
</body>
</html>
The debugger is hit on every iteration in the for loop.

Resources