I'm getting an error saying,
[$injector:unpr] http://errors.angularjs.org/1.4.1/$injector/unpr?p0=qProvider%20%3C-%20q%20%3C-%20searchResult
When I use the following config and controller. I'm trying to resolve and http request on a specific route.
.when('/fsr/:first', {
templateUrl: 'views/fsr.html',
controller: 'fsrCtrl',
resolve: {
searchResult: ['$http', 'q', function($http, $q) {
var def = $q.defer();
var samples;
$http.get('/api/fsr').success(function(data, status){
samples = data;
def.resolve(data);
})
return {
getSamples: function() {
return def.promise;
}
}
}]
}
})
.controller('fsrCtrl', ['$scope', 'searchResult', function($scope, searchResult){
searchResult.getSamples().then(function(data){
console.log(data);
})
}])
Why I'm getting this?
Here are the solution, change q to $q.
searchResult: ['$http', '$q', function($http, $q) {
...
}
var app = angular.module('webbapp', ['ngRoute']);
app.config(['$routeProvider', function ($routeProvider) {
console.log('woot');
$routeProvider
.when('/fsr', {
templateUrl: 'fsr.html',
controller: 'fsrCtrl',
resolve: {
searchResult: ['$http', '$q', function($http, $q) {
var def = $q.defer();
var samples;
$http.get('/api/fsr').success(function(data, status){
samples = data;
def.resolve(data);
})
return {
getSamples: function() {
return def.promise;
}
}
}]
}
})
}])
.controller('fsrCtrl', ['$scope', 'searchResult', function($scope, searchResult){
searchResult.getSamples().then(function(data){
console.log(data);
})
}])
angular.bootstrap(document, ['webbapp']);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>Hello Plunker!</h1>
Load Fsr view
<div ng-view=""></div>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.1/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.1/angular-route.min.js"></script>
<script src="app.js"></script>
</body>
</html>
Related
I am using angularjs 1.5.7 and keep getting below error:
angular.min.js:117 Error: [$injector:unpr] http://errors.angularjs.org/1.5.7/$injector/unpr?p0=ngTableProvider%20%3C-%20ngTable%20%3C-%20CustomerBuyController at Error (native)
The following are what I have done
**index.html**
<html ng-app="myapp">
<head>
<link href="css/vendor/ng-table.min.css" rel="stylesheet">
</head>
<body>
...
<script src="js/vendor/jquery-2.2.4.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-2.2.4.min.js"><\/script>')</script>
<script src="js/vendor/bootstrap.min.js"></script>
<script src="js/vendor/angular.min.js"></script>
<script src="js/vendor/angular-route.min.js"></script>
<script src="js/vendor/ng-table.min.js"></script>
<script src="js/app/controller-customer-buy.js"></script>
</body>
</html>
**app.js**
var app = angular.module('myapp',["ngRoute", "ngTable"]);
**route.js**
angular.module('myapp').config(function($routeProvider, $locationProvider, $httpProvider) {
var checkLoggedin = function($q, $timeout, $http, $location, $rootScope){
// Initialize a new promise
var deferred = $q.defer();
if(!sessionStorage.getItem('userToken')) {
$location.url('/login');
deferred.resolve();
} else {
$http({
method: 'POST',
url: 'http://127.0.0.1:8008/is-valid-user-token',
data: {
token: sessionStorage.getItem('userToken')
}
}).then(function successCallback(response) {
$location.url('/buy');
deferred.resolve();
}, function errorCallback(response) {
$location.url('/login');
deferred.reject();
});
}
return deferred.promise;
};
$httpProvider.interceptors.push(function($q, $location) {
return {
response: function(response) {
// do something on success
return response;
},
responseError: function(response) {
if (response.status === 401)
$location.url('/login');
return $q.reject(response);
}
};
});
$routeProvider
.when('/', {
templateUrl : 'pages/home.html'
})
.when('/login', {
templateUrl : 'pages/login.html',
controller : 'LoginController',
resolve: {
loggedin: checkLoggedin
}
})
.when('/buy', {
templateUrl : 'pages/customer-buy.html',
controller : 'CustomerBuyController',
resolve: {
loggedin: checkLoggedin
}
})
.otherwise({redirectTo: '/'});
}).run(function($rootScope, $http, $location){
// ......
});
**controller-customer-buy.js**
(function () {
'use strict';
angular.module('myapp').controller('CustomerBuyController',
['$rootScope', '$scope', '$parse', '$http', 'ngTable' ,function($rootScope, $scope, $parse, $http, ngTable) {
});
})();
I'm a new in Angularjs and developing a simple Calculator application with backend support.
Since I separate controller to controller+service - there is an error like:
Error: [$injector:unpr] http://errors.angularjs.org/1.5.0/$injector/unpr?p0=%24scopeProvider%20%3C-%20%24scope%20%3C-%20calcService
So can anyone shed light where I'm wrong ?
index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="stylesheet" type="text/css" href="bootstrap-3.0.3-dist/css/bootstrap.min.css" />
<link rel="stylesheet" type="text/css" href="css/style.css" />
<script type="text/javascript" src="js/jquery-1.12.2.min.js"></script>
<script src="angular/angular.min.js"></script>
<script type="text/javascript" src="angular/angular-ui-router.min.js"></script>
<script type="text/javascript" src="js/app.js"></script>
<script type="text/javascript" src="js/services/calcService.js"></script>
<script type="text/javascript" src="js/controllers/calcCtrl.js"></script>
<script type="text/javascript" src="js/controllers/resultsCtrl.js"></script>
</head>
<body>
<div class="container" ng-app="app">
<header ng-include="'templates/nav.html'"></header>
<div ui-view></div>
<footer ng-include="'templates/footer.html'"></footer>
</div>
</body>
</html>
app.js
angular
.module('app', [
'ui.router'
])
.config(['$urlRouterProvider', '$stateProvider', function($urlRouterProvider, $stateProvider) {
$urlRouterProvider.otherwise('/');
$stateProvider
.state('calc', {
url: '/',
templateUrl: '../templates/calc.html',
controller: 'calcCtrl'
})
.state('results', {
url: '/results',
templateUrl: '../templates/results.html',
controller: 'resultsCtrl'
})
}]);
calcCtrl.js:
angular
.module('app')
//.controller('calcCtrl', ['$scope', '$http', function($scope, $http) {
.controller('calcCtrl', ['$scope', 'calcService', function($scope, calcService) {
$scope.title = "Calculator";
$scope.items = ['calc','results'];
$scope.selectedValue = 'calc';
}]);
calcService.js:
//angular.module('app', []);
angular.module('app')
.factory('calcService', ['$scope', '$http', function($scope, $http) {
$scope.calculate = function() {
// use $.param jQuery function to serialize data from JSON
var data = $.param({
left: $scope.left,
right: $scope.right,
operation: $scope.operation
});
var config = {
headers : {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
}
}
$http.post('/calc/calculate', data, config)
.success(function (data, status) {
$scope.responseData = "Result is : " + data;
})
.error(function (data, status) {
$scope.responseData = "Data: " + data +
"<hr />status: " + status;
});
};
} ]);
Files structure: https://gyazo.com/5d571f2a92757a4c20239cb67d8b0d5c
Here is what I'm currently have with errors in firebug: https://gyazo.com/4e367b3644b0f106938f272e2980f074
If I uncomment 1st line in calcService.js - here is a result (totally hidden UI): https://gyazo.com/fb6714f5d131ab31ae0ca17509b19968
You can't inject $scope into a factory - how would it know what scope to inject? If you need to use scope data then you pass it from your controller as parameters on the factory methods. Also, your service should return the promise which you then handle in your controller.
Factory:
angular.module('app')
.factory('calcService', ['$http', function($http) {
var service = {};
service.calculate = function(left, right, operation) {
// use $.param jQuery function to serialize data from JSON
var data = $.param({
left: left,
right: right,
operation: operation
});
var config = {
headers : {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
}
}
return $http.post('/calc/calculate', data, config);
};
return service;
}]);
In your controller:
angular.module('app')
.controller('calcCtrl', ['$scope', 'calcService', function($scope, calcService) {
$scope.title = "Calculator";
$scope.items = ['calc','results'];
$scope.selectedValue = 'calc';
$scope.calculate = function(){
calcService.calculate($scope.left, $scope.right, $scope.operation).then(
function(response) {
$scope.responseData = "Data: " + response.data;
},
function(error) {
// examine the error properties and do whatever
}
);
};
}]);
All works fine if I don't inject into controller "getChildrenNumber", after then I get the error from $injector.
I've read even this https://docs.angularjs.org/error/$injector/unpr, but it seems not be one of that cases
HTML (index.html):
<html class="no-js" ng-app="myApp" ng-strict-di>
.
.
.
<script src="jsLib/angular_v1.4.js" type="text/javascript"></script>
<script src="jsLib/angular-ui-router.min.js" type="text/javascript"></script>
<script src="jsLib/angular-ui-router-statehelper.min.js" type="text/javascript"></script>
<script src="app.js" type="text/javascript"></script>
<script src="routes.js" type="text/javascript"></script>
routes.js:
var config = ["$urlRouterProvider", "$stateProvider", "$locationProvider", function($urlRouterProvider, $stateProvider, $locationProvider){
$urlRouterProvider.otherwise("/multi");
$stateProvider
.state("multi",{
url: "/multi",
views: {
"": {
templateUrl: "multipleView.htm",
controller: "MainCTRL",
controllerAs: "ctrl"
},
"viewA#multi": {
templateUrl: "testingBlock.htm",
controller: "MainCTRL",
controllerAs: "ctrl"
},
"viewB#multi": {
templateUrl: "app/templates/login.htm",
controller: ["$scope", "getChildrenNumber", function($scope, getChildrenNumber){
$scope.nameApp = "nameAppChanged";
$scope.children = getChildrenNumber + " Miao";
}]
}
},
resolve: {
getChildrenNumber: ["$http", function($http){
return "Some response from an API";
}]
}
});
}];
angular
.module("myApp")
.config(config);
app.js:
angular
.module("myApp", ["ui.router"])
.controller("MainCTRL", ["$scope", "getChildrenNumber", function($scope, getChildrenNumber){
this.nameApp = "myApp";
$scope.children = getChildrenNumber;
}]);
You are implementing it the wrong way..
Firstly, in routes.js
$stateProvider
.state("multi",{
url: "/multi",
views: {
// Views Code here //
},
resolve: {
getChildrenNumber: getChildrenNumber
}
});
}];
then you have to create your factory:
angular.module('myApp')
.factory('children', ['$http', function ($http) {
return {
getChildrenNumber: getChildrenNumber
};
function getChildrenNumber() {
return "Some response from an API";
}
}]);
After this you can inject it in your controller as children
I have the the following files:
index.html
<html ng-app="gitHubViewer">
<head>
<script data-require="angular.js#*" data-semver="1.4.0-beta.6" src="https://code.angularjs.org/1.4.0-beta.6/angular.js"></script>
<script data-require="angular-route#*" data-semver="1.4.0-beta.6" src="https://code.angularjs.org/1.4.0-beta.6/angular-route.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="app.js"></script>
<script src="MainController.js"></script>
<script src="gitHub.js"></script>
</head>
<body>
<h1>GitHub Viewer</h1>
<div ng-view>
</div>
</body>
</html>
main.html
<form name="searchUser" ng-submit="search(username)">
<input type="search" required="" placeholder="Username to find" ng-model="username" />
<input type="submit" value="Search" />
</form>
app.js
(function(angular) {
'use strict';
angular.module('gitHubViewer', ['ngRoute'])
.config(['$routeProvider',
function($routeProvider) {
$routeProvider
.when("/main", {
templateUrl: "main.html",
controller: "MainController"
})
.otherwise({
redirectTo: "/main"
});
}
]);
})(window.angular);
MainController.js
(function(angular) {
'use strict';
angular.module('gitHubViewer', [])
.controller('MainController', ['$scope', '$interval', '$location',
function($scope, $interval, $location) {
var decrementCountdown = function() {
$scope.countdown -= 1;
if ($scope.countdown < 1) {
$scope.search($scope.username);
}
};
var countdownInterval = null;
var startCountdown = function() {
countdownInterval = $interval(decrementCountdown, 1000, $scope.countdown);
};
$scope.search = function(username) {
if (countdownInterval) {
$interval.cancel(countdownInterval);
$scope.countdown = null;
}
};
$scope.username = 'angular';
$scope.countdown = 5;
startCountdown();
}
]);
})(window.angular);
My problem is that the main.html file is not being loaded on ng-view when i have the routing on a separated file (app.js).
But if i remove the app.js file and add the .config on MainController.js,the main.html loads properly, here's the example:
(function(angular) {
'use strict';
angular.module('gitHubViewer', ['ngRoute'])
.config(['$routeProvider',
function($routeProvider) {
$routeProvider
.when("/main", {
templateUrl: "main.html",
controller: "MainController"
})
.otherwise({
redirectTo: "/main"
});
}
])
.controller('MainController', ['$scope', '$interval', '$location',
function($scope, $interval, $location) {
var decrementCountdown = function() {
$scope.countdown -= 1;
if ($scope.countdown < 1) {
$scope.search($scope.username);
}
};
var countdownInterval = null;
var startCountdown = function() {
countdownInterval = $interval(decrementCountdown, 1000, $scope.countdown);
};
$scope.search = function(username) {
if (countdownInterval) {
$interval.cancel(countdownInterval);
$scope.countdown = null;
}
};
$scope.username = 'angular';
$scope.countdown = 5;
startCountdown();
}
]);
})(window.angular);
Am i doing something wrong with the separated the files???
I think you are defining your module twice with the same name, instead add a handle to it and use that.
var app = angular.module('gitHubViewer', []);
app.controller(...
app.config(...
Here's your plunkr edited to work:
plunkr
You need to declare the module that is shared between scripts outside the IIFE, so that it is a global variable to be shared. See: IIFE and scope
That is app.js now has the module defined at the top:
var app = angular.module("gitHubViewer", ["ngRoute"]);
(function() {
and this line was removed from MainController.js:
var app = angular.module("gitHubViewer", ["$scope", "$interval", "$location"]);
Note: You also don't need to inject scope or services like $location, that are included in the base angularJs package, into the module. These should be injected directly into controllers.
Note: after the countdown the plunkr now breaks, because you need to add your UserController in.
When you create a new module you use the dependency array argument
angular.module('gitHubViewer', ['ngRoute']);
Then when you want to reference the existing module you leave out the second argument.
angular.module('gitHubViewer').run...
angular.module('gitHubViewer').controller....
AngulaR resolve API
The API says for resolve:
key – {string}: a name of a dependency to be injected into the controller.
#egghead, there is this video on the topic:
egghead - Angular resolve
What i do not understand is what that key object is for and why the author of the above video does inject the controller into itself
key – {string}: a name of a dependency to be injected into the
controller.
app.config(function($routeProvider) {
$routeProvider.
when('/', {
controller: 'ListCtrl',
resolve: {
myResolve: function(MyService) {
return MyService();
}
},
templateUrl:'./views/list.html'
})
});
Instead of (in the controller)
app.controller('MyController',function($scope,MyService){
$scope.data = MyService();
});
if you use resolve
app.controller('MyController',function($scope,myResolve){
$scope.data = myResolve;
});
UPDATE
a working example
<!doctype html>
<html ng-app="myModule">
<head>
<meta charset="utf-8">
</head>
<body>
<div id="content" data-ng-view=""></div>
<script src="http://code.angularjs.org/1.0.8/angular.min.js"></script>
<script>
var myModule = angular.module('myModule', []);
myModule.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: './index.html',
controller: 'IndexCtrl',
resolve: {
hello: function(Hello) {
return Hello.getMessages();
}
}
})
.otherwise({
redirectTo: '/'
});
});
myModule.factory('Hello', function($q, $timeout) {
var getMessages = function() {
var deferred = $q.defer();
$timeout(function() {
deferred.resolve('Hello');
}, 1000);
return deferred.promise;
};
return {
getMessages: getMessages
};
});
myModule.controller('IndexCtrl',function($scope,hello){
$scope.hello = hello;
});
</script>
</body>
</html>
the view
<p>{{hello}}</p>