I am following this angular, jquery, bootstrap pagination tutorial http://jsfiddle.net/ef0d9zuk/1/ that I found through a related post. The tutorial example works yet I am receiving a error message Uncaught Error: [$injector:modulerr] Failed to instantiate module GithubIssues due to:
Error: [$injector:modulerr] Failed to instantiate module Pages due to:
Error: [$injector:nomod] Module 'Pages' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.
Can anyone tell me what I am doing wrong here?
var defaultPage = angular.module('GithubIssues', [
'ngRoute',
'DefaultPage'
]);
defaultPage.config(['$routeProvider', function ($routeProvider) {
$routeProvider.
when('/default', {
templateUrl: 'partials/default.html',
controller: 'DefaultController'
}).
when('/issues/:issueId', {
templateUrl: 'partials/issues.html',
controller: 'IssuesController'
}).
otherwise({
redirectTo: '/default'
});
}]);
// declaring my DefaultController for default page and params
defaultPage = angular.module('DefaultPage', ['pages']);
angular.module('pages', []).factory('Pages', function () {
return {
getPage: function (pageNum) {
var pageData = $scope.ctrl.info + pageNum;
}
return pageData;
}
});
defaultPage.controller('DefaultController', ['$scope', '$http', 'Pages', function ($scope, $http, Pages) {
$scope.data = {};
var url = 'https://api.github.com/repos/npm/npm/issues'
$http.get(url, {
headers: {
'Content-type': 'application/json'
}
}).success(function (data) {
$scope.ctrl.info = data;
$scope.currentPage = 0;
$scope.pageSize = 10;
$scope.numberOfPages = function () {
return 25;
};
$scope.data = Pages.getPage($scope.currentPage);
$scope.getPage = function (pageNum) {
$scope.data = Pages.getPage(pageNum);
}
/* $scope.itemsPerPage = 26;
$scope.currentPage = 1;*/
/*$scope.makeTodos = function() {
$scope.GithubIssues = [];
for (var i = 1; i <= $scope.ctrl.info.length; i++) {
$scope.GithubIssues.push({ $scope.ctrl.info, done:false});
}
};*/
/* $scope.figureOutTodosToDisplay = function() {
var begin = (($scope.currentPage - 1) * $scope.itemsPerPage);
var end = begin + $scope.itemsPerPage;
$scope.ctrl.info = $scope.ctrl.info.slice(begin, end);
console.log(data);
; };*/
/*$scope.makeTodos();*/
/*$scope.figureOutTodosToDisplay();
$scope.pageChanged = function() {
$scope.figureOutTodosToDisplay();
};*/
});
}]); //defaultPage ctrl end
defaultPage.filter('startFrom', function () {
return function (input, start) {
start = +start;
return input.slice(start);
}
});
// declaring my IssuesController for my issues page and params
defaultPage.controller('IssuesController', ['$scope', '$http', '$routeParams', function ($scope, $http, $routeParams) {
$http.get('https://api.github.com/repos/npm/npm/issues')
.success(function (data) {
$scope.ctrl = data;
$scope.whichIssue = $routeParams.issueId;
//Issue page previous issue button
if ($routeParams.issueId > 0) {
$scope.prevIssue = Number($routeParams.issueId) - 1;
} else {
$scope.prevIssue = $scope.ctrl.length - 1;
}
//Issue page next issue button
if ($routeParams.issueId < $scope.ctrl.length - 1) {
$scope.nextIssue = Number($routeParams.issueId) + 1;
} else {
$scope.nextIssue = 0;
}
});
}]); // end
Removing the line
defaultPage = angular.module('DefaultPage', ['pages']);
and changing 'DefaultPage' dependency to 'pages' at
var defaultPage = angular.module('GithubIssues', [
'ngRoute',
'DefaultPage'
]);
will resolve dependency errors. The reason for error is defaultPage name is used twice for two different module.
Seem to be injecting a dependency before registering it
Change order of:
defaultPage = angular.module('DefaultPage', ['pages']);
angular.module('pages', []).factory('Pages', function () {
return {
getPage: function (pageNum) {
var pageData = $scope.ctrl.info + pageNum;
}
return pageData;
}
});
To
angular.module('pages', []).factory('Pages', function () {
return {
getPage: function (pageNum) {
var pageData = $scope.ctrl.info + pageNum;
}
return pageData;
}
});
defaultPage = angular.module('DefaultPage', ['pages']);
Related
I'm trying to put the HTTP request in a service file in order to use this function in multiple controllers but I get the error below, I tried multiple solutions but still get this error
here is my controller.js
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/LatestMovies', {
templateUrl: 'LatestMovies/LatestMovies.html',
controller: 'LatestMoviesCtrl'
});
}])
.controller('LatestMoviesCtrl',
['myServices','$scope',function(myServices,$scope) {
$scope.movies = myServices.getLatestMovies();
console.log($scope.movies ,'ggg')
}
]);
here is my services.js
angular.module('myApp', ['ngRoute'])
.factory('myServices', function ($http) {
return {
getLatestMovies : function () {
var service ={
movies : '',
details : []
}
var base = 'http://api.themoviedb.org/3';
var service = '/movie/popular?page=1&language=en-
US&api_key=';
var apiKey = '';
var callback = 'JSON_CALLBACK';
var url =base + service + apiKey + '&callback=' + callback;
//$scope.results = 'requesting...';
$http.jsonp(url).then(function(result, status) {
//$scope.results = JSON.stringify(data);
service.movies = result.data;
angular.forEach(result.data.results, function (value,
index) {
service.details.push(value);
});
},function(result, status) {
service.movies = 'Maybe you missed your API key?' +
JSON.stringify(result.data);
});
return service.movies;
}
}
});
error
angular.js:14199 Error: [$injector:unpr] Unknown provider: myServicesProvider <- myServices <- LatestMoviesCtrl
http://errors.angularjs.org/1.5.11/$injector/unpr?p0=myServicesProvider%20%3C-%20myServices%20%3C-%20LatestMoviesCtrl
at http://localhost:8000/bower_components/angular/angular.js:68:12
at http://localhost:8000/bower_components/angular/angular.js:4563:19
at Object.getService [as get] (http://localhost:8000/bower_components/angular/angular.js:4716:32)
at http://localhost:8000/bower_components/angular/angular.js:4568:45
at getService (http://localhost:8000/bower_components/angular/angular.js:4716:32)
at injectionArgs (http://localhost:8000/bower_components/angular/angular.js:4741:58)
at Object.instantiate (http://localhost:8000/bower_components/angular/angular.js:4783:18)
at $controller
you need to inject the $http module to send api call
.factory('myServices', ['$http',function ($http) {
return {
getLatestMovies : function () {
var service ={
movies : '',
details : []
}
var base = 'http://api.themoviedb.org/3';
var service = '/movie/popular?page=1&language=en-
US&api_key=';
var apiKey = '';
var callback = 'JSON_CALLBACK';
var url =base + service + apiKey + '&callback=' + callback;
//$scope.results = 'requesting...';
$http.jsonp(url).then(function(result, status) {
//$scope.results = JSON.stringify(data);
service.movies = result.data;
angular.forEach(result.data.results, function (value,
index) {
service.details.push(value);
});
},function(result, status) {
service.movies = 'Maybe you missed your API key?' +
JSON.stringify(result.data);
});
return service.movies;
}
}
}]);
It seems like you have been creating myApp module twice, first in services.js and then in controller.js. So basically what happens is
When services.js loaded first, it creates myApp angular module with myServices service.
And when controllers.js file loaded, at the beginning of file you have recreated myApp module using angular.module('myApp', ['ngRoute']). Where it recreate a new myApp module and register config & LatestMoviesCtrl to it.
Hence myServices dependency isn't available.
To fix the issue while registering further files.
angular.module('myApp')
.config(...)
.controller('LatestMoviesCtrl', .... )
I am having problem while injecting dependency from service to controller. Although i added it but still same error of
Unknown provider: websiteFactoryProvider <- websiteFactory <- listCtrl
I basically need to render a ng-view to my index.html
Index.html
<div ng-view>
</div>
app.js
var app = angular.module('app', ['ngRoute']);
app.config(['$routeProvider', function ($routeProvider) {
$routeProvider.
when('/list', {
templateUrl: 'app/views/list.html', controller: 'listCtrl'
}).
otherwise({
redirectTo: '/list'
});
}]);
websiteService.js
app.factory('webiteFactory', ['$http', '$location', function ($http, $location) {
var factory = {};
// method that return all websites from an http request
factory.getAllWebsites = function () {
return $http.get("http://localhost/Replicate/GetAllWebsites");
}
//method that returns an object from given array
factory.getFilteredObject = function (list, websiteName) {
for (i = 0 ; i < list.length ; i++) {
if (list[i].Name == websiteName)
return list[i];
}
}
return factory;
}]);
/* application services that would not return values */
app.service('websiteService', ['$http', function ($http) {
//service for pagination
this.paginate = function ($scope) {
//pagination code
$scope.currentPage = 1;
$scope.totalItems = $scope.model.length;
$scope.numPerPage = 10;
$scope.paginate = function (value) {
var begin, end, index;
begin = ($scope.currentPage - 1) * $scope.numPerPage;
end = begin + $scope.numPerPage;
index = $scope.model.indexOf(value);
return (begin <= index && index < end);
};
//ordering code
$scope.reverse = true;
$scope.order = function (predicate) {
$scope.reverse = ($scope.predicate === predicate) ? !$scope.reverse : false;
$scope.predicate = predicate;
};
}
//service to change state of a website
this.changeSiteState = function (website) {
var newState = website.State == "Stopped" ? "Started" : "Stopped";
$http({
method: 'POST',
url: '/Replicate/ChangeState/',
data: JSON.stringify({ webName: website.Name, state: newState }),
headers: { 'Content-Type': 'application/json' }
}).success(function (data) {
if (data == "success") {
website.State = website.State == "Stopped" ? "Started" : "Stopped";
}
else {
alert(data);
}
}).error(function (data, status, headers, config) {
alert(data);
});
}
}])
listCtrl.js
app.controller('listCtrl', function websiteCtrl($scope, $location, websiteFactory, websiteService, $modal) {
//function triggered at the intialization of controller
$scope.init = function () {
$scope.model = [];
setTimeout(function () {
websiteFactory.getAllWebsites().success(function (data) {
$scope.model = data;
websiteService.paginate($scope);
})
}, 0);
};
//delegation of change state to service method
$scope.changeState = function (website) {
websiteService.changeSiteState(website);
}
//open modal and shows details of single object
$scope.showDetails = function (websiteName) {
var modalInstance = $modal.open({
templateUrl: '../Views/Replicate/Details.html',
controller: 'DetailsCtrl',
resolve: {
obj: function () {
return websiteFactory.getFilteredObject($scope.model, websiteName);
}
}
});
}
});
You have misspelled "websiteFactory". In your factory definition code it is "webiteFactory" but in controller you are fetching it with different name using "websiteFactory" that's why it is not able to find this provider and producing error:
change:
app.factory('websiteFactory', ['$http', '$location', function ($http, $location) {
var factory = {};
// method that return all websites from an http request
factory.getAllWebsites = function () {
return $http.get("http://localhost/Replicate/GetAllWebsites");
}
//method that returns an object from given array
factory.getFilteredObject = function (list, websiteName) {
for (i = 0 ; i < list.length ; i++) {
if (list[i].Name == websiteName)
return list[i];
}
}
return factory;
}]);
That error comes when your factory is not registered with angular . Change it to
app.factory('websiteFactory', ['$http', '$location', function ($http, $location) {
...do something here...
}
What specific changes need to be made to the AngularJS code below to check for the existence of a cookie named myCookie every time a page is loaded, and then to set the $rootScope.myCookieValue variable to become the value of myCookie?
The code is from the sample app whose complete code you can explore at this link. It is a very simple example app, and I just want a simple working solution to this so that I can build up more complex approaches from it.
angular.module('hello', [ 'ngRoute' ]).config(function($routeProvider, $httpProvider) {
$routeProvider.when('/', {
templateUrl : 'home.html',
controller : 'home',
controllerAs : 'controller'
}).otherwise('/');
$httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
$httpProvider.defaults.headers.common['Accept'] = 'application/json';
}).controller('navigation',
function($rootScope, $http, $location, $route) {
var self = this;
self.tab = function(route) {
return $route.current && route === $route.current.controller;
};
$http.get('user').then(function(response) {
if (response.data.name) {
$rootScope.authenticated = true;
} else {
$rootScope.authenticated = false;
}
}, function() {
$rootScope.authenticated = false;
});
self.credentials = {};
self.logout = function() {
$http.post('logout', {}).finally(function() {
$rootScope.authenticated = false;
$location.path("/");
});
}
}).controller('home', function($http) {
var self = this;
$http.get('resource/').then(function(response) {
self.greeting = response.data;
})
});
you can do it in run block I guess:
angular.module('hello', ['ngCookies', 'ngRoute'])
.config(function ($routeProvider, $httpProvider) {
$routeProvider.when('/', {
templateUrl: 'home.html',
controller: 'home',
controllerAs: 'controller'
}).otherwise('/');
$httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
$httpProvider.defaults.headers.common['Accept'] = 'application/json';
}).run(function ($rootScope, $cookies) {
var cookieValue = $cookies.get("myCookie");
if (cookieValue) {
$rootScope.myCookieVar = cookieValue;
}
}).controller('navigation',
function ($rootScope, $http, $location, $route) {
var self = this;
self.tab = function (route) {
return $route.current && route === $route.current.controller;
};
$http.get('user').then(function (response) {
if (response.data.name) {
$rootScope.authenticated = true;
} else {
$rootScope.authenticated = false;
}
}, function () {
$rootScope.authenticated = false;
});
self.credentials = {};
self.logout = function () {
$http.post('logout', {}).finally(function () {
$rootScope.authenticated = false;
$location.path("/");
});
}
}).controller('home', function ($http) {
var self = this;
$http.get('resource/').then(function (response) {
self.greeting = response.data;
})
});
I think you should use angular version > 1.4.x
you should also add reference angular-cookies.js
I am trying to redirect users to a login page if they make an attempt to access pages that require them to be logged in. I am using Firebase and AngularJS, following this guide. The error explanation on the AngularJS site indicates that either a non-existent definition or duplicate definition is causing the issue but I cannot identify either of these in my code. Additionally, the stack trace of the error doesn't indicate which of my files caused the error, only mentioning the angular.js file.
Can anyone give me some insight as to what is causing this issue?
Note: The site runs without errors and users can log in and out if I leave out the resolve section of the $routeProvider.
Here is my app.js
angular.module('richWebApp', ['ngRoute', 'firebase', 'objectFilter'])
.constant('fb', {
url: 'https://<my-firebase-app>.firebaseio.com/' //name removed for security reasons
})
.run(function($rootScope, $location) {
$rootScope.$on("$routeChangeError", function(event, next, previous, error) {
if(error === "AUTH_REQUIRED") {
$location.path("/login");
}
});
})
.config(function($routeProvider){
$routeProvider.
when('/login', {
templateUrl: 'pages/login/login.html'
}).
when('/main', {
templateUrl: 'pages/main/main.html',
resolve: {
"currentAuth": ["Auth", function(Auth) {
return Auth.$requireAuth();
}]
}
}).
when('/thread/:threadId', {
templateUrl: 'pages/thread/thread.html',
resolve: {
"currentAuth": ["Auth", function(Auth) {
return Auth.$requireAuth();
}]
}
}).
otherwise({
redirectTo: '/login'
});
});
Here is the main.js controller
angular.module('richWebApp')
.controller('mainPageController', function($scope, $location, userService, currentAuth, threadService, fb, $firebaseAuth, $filter){
$scope.user = userService.getLoggedInUser();
$scope.newThreadTitle = '';
$scope.threadSubject = ''
$scope.createNewThread = false;
$scope.sortBy = 'dateAdded'
$scope.threads = threadService.getAllThreads();
$scope.getSubjects = function(subject) {
return $scope.threads.subject;
}
$scope.beginAddThread = function() {
$scope.createNewThread = true;
}
$scope.addThread = function(){
if(!$scope.newThreadTitle || !$scope.newThreadSubject){
return false;
}
var date = new Date();
var newThread = {
title: $scope.newThreadTitle,
subject: $scope.newThreadSubject,
username: $scope.user.name,
numComments: 0,
comments: [],
dateAdded: date.getTime()
};
$scope.threads.$add(newThread);
$scope.newThread = '';
$scope.newThreadTitle = '';
$scope.newThreadSubject = '';
$scope.createNewThread = false;
}
$scope.sortByDate = function() {
$scope.sortBy = 'dateAdded';
}
$scope.sortByPopularity = function() {
$scope.sortBy = 'numComments';
}
$scope.searchSubject = function(subject) {
$scope.searchThread = subject;
}
$scope.logout = function(){
userService.logout();
}
});
Here is the thread.js controller
angular.module('richWebApp')
.controller('threadPageController', function($scope, $location, $routeParams, $filter, currentAuth, threadService, fb, userService){
var threadId = $routeParams.threadId;
$scope.newComment = '';
var thread = threadService.getThread(threadId);
thread.$bindTo($scope, 'thread')
$scope.addComment= function(){
if(!$scope.newComment){
return false;
}
var currentUser = userService.getLoggedInUser();
var date = new Date();
var newComment = {
text: $scope.newComment,
username: currentUser.name,
dateAdded: date.getTime(),
userPic: currentUser.profilePic
};
$scope.thread.comments = $scope.thread.comments || [];
$scope.thread.comments.push(newComment);
$scope.thread.numComments += 1;
$scope.newComment = '';
}
});
Your code is referring to an Auth factory, which is shown in the example under Retrieving Authentication State. Include this in your code.
.factory("Auth", ["$firebaseAuth",
function($firebaseAuth) {
var ref = new Firebase("<YOUR FIREBASE>");
return $firebaseAuth(ref);
}
]);
I have an angular controller called SubmissionTreeController and it has update_dashboard() function which refreshes the ui every minute.
My goal is to refresh the ui on successful post request from a different controller.
How do I make this function available in other controllers?
var module = angular.module("submissionDashboard", ['ui.tree', 'ngCookies', 'ui.bootstrap',]);
module.controller("SubmissionTreeController", ["$scope", "$http", "$modal",
function($scope, $http, $modal) {
$scope.selected_items = {};
var update_dashboard = function() {
var url = Django.url('submission:active_list_ajax', {
site : site
});
$http.get(url).success(function(data) {
$scope.list = data.results;
});
};
update_dashboard();
$scope.closeTask = function(scope) {
var modalInstance = $modal.open({
templateUrl: 'modal_close_submission_renderer.html',
controller: 'ModalCloseSubmissionController',
resolve: {
items: function () {
return $scope.selected_items;
}}
});
};
}]);
module.controller('ModalCloseSubmissionController', ['$scope', '$modalInstance', '$http', 'items', function ($scope, $modalInstance, $http, items) {
$scope.items = items;
$scope.selected = {
item: 1,
text: ''
};
$scope.ok = function () {
var val = $scope.selected.item;
if (val === 1) {
var url = Django.url('submission:close-notify', {
site : site
});
$http.post(url, $scope.selected_items).success(function(data) {
update_dashboard();
});
} else if (val === 2) {
var url = Django.url('submission:close', {
site : site
});
$http.post(url, $scope.selected_items).success(function(data) {
update_dashboard();
});
} else if (val === 3) {
var url = Django.url('submission:cancel', {
site : site
});
$http.post(url, $scope.selected_items).success(function(data) {
update_dashboard();
});
};
$modalInstance.close($scope.selected.item);
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
}]);
Edit:
What I am trying to do:
module.service('updateDashboardService', function($scope, $http){
this.update_dashboard = function() {
$scope = $scope;
var url = Django.url('submission:active_list_ajax', {
site : site
});
$http.get(url).success(function(data) {
$scope.list = data.results;
});
};
});
module.controller("SubmissionTreeController", ["$scope", "$http", "$modal", "updateDashboardService", function($scope, $http, $modal, updateDashboardService) {
$scope.selected_items = {};
updateDashboardService.update_dashboard();
var timer = setInterval(function() {
$scope.$apply(updateDashboardService.update_dashboard($scope, $http));
}, 1000 * 60);
What I am getting:
Error: [$injector:unpr] Unknown provider: $scopeProvider <- $scope <- updateDashboardService
Edit 2:
module.service('updateDashboardService', function($rootScope, $http){
this.update_dashboard = function() {
var url = Django.url('submission:active_list_ajax', {
site : site
});
$http.get(url).success(function(data) {
$rootScope.list = data.results;
});
};
});
As #Gopesh says create a factory method, or, you can do something like this in SubmissionTreeController:
$scope.$on("event:updateDashboard", function(){ update_dashboard() });
And in your other controller:
$http.post(url, $scope.selected_items).success(function(data) {
$scope.$emit("event:updateDashboard");
});