I am trying to create a pagination for my page using angularjs framework. Currently, I am getting the error that Error: [$injector:unpr] Unknown provider: setPageProvider <- setPage. I tried changing the arrangement of the code but it still the same. I tried to follow the tutorial from this website but its not working. Can i know the way to solve this problem. Thanks in advance.
This is my controller.js code:
(function () {
angular.module('myApp', ['MovieApp']).
filter('startFrom', function() {
return function(input, start) {
if(input) {
start = +start; //parse to int
return input.slice(start);
}
return [];
}
}
);
"use strict";
angular.module('MovieApp').
controller('SearchController',
[
'$scope',
'dataService',
'$location',
'$routeParams',
'$timeout',
'setPage',
'$filter',
function ($scope, dataService, $location, $routeParams, $timeout, $setPage, $filter){
$scope.searchMovies = [ ];
$scope.searchCount = 0;
var getSearchResult = function () {
dataService.getSearchResult().then(
function (response) {
$scope.searchCount = response.rowCount + ' movies';
$scope.searchMovies = response.data;
$scope.showSuccessMessage = true;
$scope.successMessage = "All movie Success";
$scope.currentPage = 1; //current page
$scope.entryLimit = 5; //max no of items to display in a page
$scope.filteredItems = $scope.searchMovies.length; //Initially for no filter
$scope.totalItems = $scope.searchMovies.length;
},
function (err){
$scope.status = 'Unable to load data ' + err;
}
); // end of getStudents().then
};
$scope.setPage = function(pageNo) {
$scope.currentPage = pageNo;
};
$scope.filter = function() {
$timeout(function() {
$scope.filteredItems = $scope.filtered.length;
}, 10);
};
getSearchResult();
}
]
);
}());
This is my search.html code:
<div>
<label>Search: <input ng-model="searchMovie" ng-change="filter()"></label><br><br><br><br>
</div>
<div ng-show="filteredItems > 0">
<table class="table table-hover table-bordered">
<thead>
</thead>
<tbody>
<tr ng-repeat="searchmovie in filtered = (searchMovies | filter:searchMovie) | startFrom:(currentPage-1)*entryLimit | limitTo:entryLimit">
</tr>
</tbody>
</table>
</div>
<div ng-show="filteredItems > 0">
<div pagination="" page="currentPage" on-select-page="setPage(page)"
boundary-links="true" total-items="filteredItems" items-per-page="entryLimit"
previous-text="«" next-text="»">
</div>
</div>
I am trying to add the pagination for the page so that i can see the result in the table as in a page.
You're injecting setPage in your SearchController, but the service/factory doesn't exist.
In your controller 'SearchController' you are injecting 'setPage' and $setPage. Remove both injections.
EDIT:
angular.module('MovieApp')
.controller('SearchController',
['$scope', 'dataService', '$location', '$routeParams', '$timeout', '$filter'
, function ($scope, dataService, $location, $routeParams, $timeout, $filter){
// Some code..
}]);
I have solved the problem by myself. I had to reedit the module code in my controller.js file. This is the solution for it
var app = angular.module('MovieApp');
app.filter('startFrom', function() {
return function(input, start) {
if(input) {
start = +start; //parse to int
return input.slice(start);
}
return [];
}
});
Related
I am trying to use the angularjs $broadcast property to hide my table columns. If the data is broadcasted the table column should be shown else the table column should be hidden. Currently if i run my code, once login i broadcasted my login username to the function but still my whole table is not showing. Can i know a way to solve it.
This is my controller.js code:
.controller('AllMovieController',
[
'$scope',
'dataService',
'$location',
'$rootScope',
function ($scope, dataService, $location, $rootScope){
$scope.noteEnabled = false;
$scope.movies = [ ];
$scope.movieCount = 0;
$scope.currentPage = 0; //current page
$scope.entryLimit = 20; //max no of items to display in a page
var getAllMovie = function () {
dataService.getAllMovie().then(
function (response) {
$scope.$on("passuser", function ($event, data ){
if(data){
$scope.movies = response.data;
$scope.showSuccessMessage = true;
$scope.successMessage = "All movie Success";
$scope.noteEnabled = true;
}else{
$scope.movies = response.data;
$scope.noteEnabled = false;
}
});
},
function (err){
$scope.status = 'Unable to load data ' + err;
}
); // end of getStudents().then
};
$scope.numberOfPages = function(){
return Math.ceil($scope.movies.length / $scope.entryLimit);
};
getAllMovie();
}
]
)
This is my partial html code:
<table class="table table-hover table-bordered">
<thead>
<tr>
<th>Title</th>
<th>Description</th>
<th ng-show="noteEnabled">Notes</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="movie in movies | pagination: currentPage * entryLimit |
limitTo: entryLimit">
<td>
{{movie.title}}
</td>
<td>
{{movie.description}}
</td>
<td data-ng-click="selectFilmDetails($event,movie)" ng-show="noteEnabled" >
{{movie.comment}}
</td>
</tr>
</tbody>
</table>
This is the broadcasted controller code:
.controller('LoginController',
[
'$scope',
'dataService',
'$location',
'$window',
'$rootScope',
function ($scope, dataService, $location, $window, $rootScope){
$scope.check_login = function($event,userID,passwd){
dataService.login(userID,passwd).then(
function (response){
if(response.result.status=='ok'){
$scope.user = response.user;
$rootScope.$broadcast("passuser", $scope.user);
$location.path('#/home');
//$window.location.reload();
}else{
$scope.message = response.result.message;
}
},
function (err) {
$scope.status = 'unable to connect to data' + err;
}
);
}//end of function check_login
}
]
)
Previously, i used session to check whether the user is logged in, but now i am using broadcast to pass the username to the controller. And the same i tried to pass the username to this controller its not working. I really need a help on this. Thanks in advance.
I would recommend moving your event listener outside the .then() of your getAllMovie() service call. What happens if the passuser event is broadcast before that promise resolves? Here's how I would recommend restructuring your code (I removed the modules you were injecting, but not using):
Update: The issue may be that your controller that has the event listener isn't instantiated when you are broadcasting the event. This is a guess because it's unclear if these are one view, different views, etc. I would suggest storing the logged in status in a value instead. This is just one example - it may not be the best way or one that will address all of what you need. I haven't tested this so you may have to play around with it to get it to work the way you want. Here is my updated recommended code:
.value('UserInfo', { user: '', loggedIn: false })
.controller('LoginController',
['$scope', 'dataService', '$location', 'UserInfo',
function ($scope, dataService, $location, UserInfo) {
$scope.check_login = function($event,userID,passwd) {
dataService.login(userID,passwd).then(
function (response){
if(response.result.status=='ok'){
UserInfo.user = response.user;
UserInfo.loggedIn = true;
$location.path('#/home');
} else {
$scope.message = response.result.message;
UserInfo.user = '';
UserInfo.loggedIn = false;
}
},
function (err) {
$scope.status = 'unable to connect to data' + err;
UserInfo.user = '';
UserInfo.loggedIn = false;
});
}//end of function check_login
}])
.controller('AllMovieController', ['$scope', 'dataService', 'UserInfo',
function ($scope, dataService, UserInfo) {
$scope.noteEnabled = false;
$scope.movies = [];
$scope.movieCount = 0;
$scope.currentPage = 0; //current page
$scope.entryLimit = 20; //max no of items to display in a page
$scope.noteEnabled = UserInfo.loggedIn;
var getAllMovie = function () {
dataService.getAllMovie().then(
function (response) {
$scope.movies = response.data;
$scope.showSuccessMessage = true;
$scope.successMessage = "All movie Success";
},
function (err) {
$scope.status = 'Unable to load data ' + err;
});
};
$scope.numberOfPages = function() {
return Math.ceil($scope.movies.length / $scope.entryLimit);
};
getAllMovie();
}]);
I am having problems injecting ServicesData into SearchCtrl, and keep getting the following error message: Error: [$injector:unpr] Unknown provider: ServicesDataProvider <- ServicesData <- SearchCtrl. What could be the cause of this?
app.js
angular.module('starter', ['ionic', 'jett.ionic.filter.bar', 'starter.controllers'])
.state('app.playlists', {
url: '/playlists',
views: {
'menuContent': {
templateUrl: 'templates/playlists.html',
controller: 'SearchCtrl'
}
}
});
});
controller.js
angular.module('starter.controllers', [])
.controller('AppCtrl', function($scope, $ionicModal, $timeout) {
})
.controller('SearchCtrl', ["$scope", "ServicesData", function($scope, $timeout, ServicesData, $ionicFilterBar) {
// Get list items
function getItems () {
var items = [];
for (var x = 1; x < 3; x++) {
items.push({text: 'Item number ' + x});
}
$scope.items = items;
}
getItems();
// Ionic filter bar
var filterBarInstance;
$scope.visible = true;
$scope.nulledVisible = false;
$scope.toggle = function(event) {
if(event.target.id === 'nulled-search-button' && $scope.nulledVisible === false || event.target.id === 'header-search-button' && $scope.nulledVisible === false) {
$scope.visible = !$scope.visible;
$scope.nulledVisible = true;
}
};
$scope.showFilterBar = function () {
filterBarInstance = $ionicFilterBar.show({
items: $scope.items,
update: function (filteredItems, filterText) {
$scope.items = filteredItems;
if (filterText) {
console.log(filterText);
}
}
});
};
$scope.refreshItems = function () {
if (filterBarInstance) {
filterBarInstance();
filterBarInstance = null;
}
$timeout(function () {
getItems();
$scope.$broadcast('scroll.refreshComplete');
}, 1000);
};
}]);
services.js
angular.module('starter.services', [])
.service("ServicesData", [function () {
var servicesData = [
{
title: 'Car Repair and Maintenance',
total: 7,
id: 1
}
];
return {
getAllServices: function () {
return servicesData;
}
}])
2 things :
fix your controller declaration
["$scope", "ServicesData", function($scope, $timeout, $ionicFilterBar)
["$scope", "ServicesData", "$timeout", "$ionicFilterBar", function($scope, ServicesData, $timeout, $ionicFilterBar)
add dependency to your service module so your controller iwll be able to access what have been declared in your start.services module.
angular.module('starter.controllers', ['starter.services'])
Seems like you have an DI problem. Try to change this:
.controller('SearchCtrl', ["$scope", "ServicesData", function($scope, $timeout, ServicesData, $ionicFilterBar)
to:
.controller('SearchCtrl', ["$scope", "$timeout", "ServicesData", "$ionicFilterBar", function($scope, $timeout, ServicesData, $ionicFilterBar)
Rewrite dependency injection line.
.controller('SearchCtrl', ["$scope","$timeout","ServicesData", $ionicFilterBar, function($scope, $timeout, ServicesData, $ionicFilterBar)
the problem is sequence should be same and you have write dependency in both places.
I am trying to achieve category sorting in Angular js but its not working properly. It pulls data from desciption as well. I want to restrict it to categories names but no luck.
JS code:
var myApp = angular.module('myApp', []);
myApp.factory('Items', ['$http', function($http){
return {
get: function(callback){
$http.get('items.json').success(function(data){
callback(data);
})
}
}
}]);
myApp.factory('Categories', ['$http', function($http){
return {
get: function(callback){
$http.get('categories.json').success(function(data){
callback(data);
})
}
}
}]);
// Config and Routes
myApp.config(function($routeProvider){
$routeProvider
.when('/', {
templateUrl:"home.html"
})
.when('/item/:id', {
templateUrl:"item.html"
})
})
myApp.controller('headerController', function($scope, $location) {
$scope.goHome = function () {
$location.path('/');
};
})
function Ctrl($scope) {
$scope.greeting = 'hello';
}
// Controllers
myApp.controller('ItemController', function($scope, $route, $location, $http, Items){
Items.get(function(response){
$scope.items = response;
});
// Update this value dynamically - onclick
$scope.filters = "food";
$scope.viewDetail = function(item) {
$location.path('/item/' + item.id);
}
})
myApp.controller('ListController', function($scope, $route, $location, $http, Categories){
$scope.sendCategory = function(category) {
// How can I pass this value to ItemController?
$scope.search =category.name;
};
$scope.orderProp='date';
$scope.tab = function (tabIndex) {
//Sort by date
if (tabIndex == 1){
//alert(tabIndex);
$scope.orderProp='date';
}
//Sort by views
if (tabIndex == 2){
$scope.orderProp = 'views';
}
};
$scope.sort = function(item) {
if ( $scope.orderProp == 'date') {
return new Date(item.date);
}
return item[$scope.orderProp];
}
})
myApp.controller('CategoryController', function($scope, $route, $location, $http, Categories){
Categories.get(function(response){
$scope.categories = response;
});
})
myApp.controller("tabsController", function ($scope) {
$scope.orderProp = 'date';
})
myApp.controller('ItemDetailController', function($scope, $route, $location, $http, Items){
Items.get(function(response){
$scope.items = response;
if ($route.current.params.id) {
angular.forEach($scope.items, function (v, k) {
if (v.id == $route.current.params.id) {
$scope.currItem = $scope.items[k];
return false;
}
});
}
});
})
can any one please help to find the way I can sort the data only as per my category names instead searching data on the overall pages?
Sharing the reference URL I found for this.
http://plnkr.co/edit/rh3wGYhuoHSHJEa4PoQi?p=preview
It would be great help if any can help me out.
I am trying to use $rootScope.$watchCollection in my code to update the data in controller B from controller A . but i am not getting any successful in it. as my application got stuck at this point ,so i am seeking your help so that i can came to know that where i am going wrong in code.
Controller B :-
app.controller('MenuCtrl', function($scope, LocalStorage, $stateParams,
$rootScope) {
$scope.user = {};
$scope.user.userName = LocalStorage.getData("userName");
$scope.user.profilePic = LocalStorage.getData("userProfile");
$rootScope.$watchCollection(function(n, o) {
if (n !== o) {
var list = $rootScope.wholecartList;
alert("Length " + list.length);
}
});
});
Controller A :-
app.controller('ProductCtrl', function($http, $scope, $ionicPopup, $state,
$ionicHistory, $ionicLoading, DataService, LocalStorage, $stateParams,
ProductId, DuplicateCheck, $rootScope) {
$scope.productList = DataService.getProducts();
$scope.getProductId = function(productId) {
ProductId.addProductId(productId);
$state.go("app.products-details");
}
var cartList = [];
$scope.cartListItems = function(product) {
if (cartList.length > 0) {
if (!DuplicateCheck.getProducts(product.product_id, cartList)) {
cartList.push(product);
}
} else {
cartList.push(product);
}
$rootScope.wholecartList = cartList;
}
});
Any help will be greatly appreciated
Thanks.
After this you need to update the $rootScope (say, run the apply cycle);
app.controller('ProductCtrl', function($http, $scope, $ionicPopup, $state,
$ionicHistory, $ionicLoading, DataService, LocalStorage, $stateParams,
ProductId, DuplicateCheck, $rootScope) {
$scope.productList = DataService.getProducts();
$scope.getProductId = function(productId) {
ProductId.addProductId(productId);
$state.go("app.products-details");
}
var cartList = [];
$scope.cartListItems = function(product) {
if (cartList.length > 0) {
if (!DuplicateCheck.getProducts(product.product_id, cartList)) {
cartList.push(product);
}
} else {
cartList.push(product);
}
$rootScope.wholecartList = cartList;
updateRootScope();
}
function updateRootScope(){
if(!$rootScope.$$phase){
$rootScope.$apply();
}
}
});
I want to call a method from one controller to another controller. There are two controllers named "header" and "mainContent". Need to call a "trigger method" in the "header Controller", After the success call of "result method" in the mainController.
If that method called that should hide that paragraph.
<div ng-controller="header">
<p ng-show="msg">Content</p>
</div>
<div ng-controller="mainContent">
</div>
var module = angular.module("sourceViewer", ['ui.router']);
//header controller
module.controller('header', function ($scope, $location) {
$scope.msg=true;
$scope.trigger= function(data) { //This method should be called after the result method called in the mainContent Controller
$scope.$on('UPDATE_CHILD', function() {
if(data)
$scope.msg=false;
});
}
});
// mainContent controller
module.controller('mainContent', function ($scope, $location, dataService) {
$scope.user = dataService.user;
$scope.signIn = function (user) {
var result = dataService.login(user);
result.success(function (data) {
if (data.message== "success") {
$scope.$broadcast('UPDATE_CHILD');
//From here I want to call trigger method of header controller
}
})
};
});
did u try this?
module.controller('header', ['$scope', '$location', '$rootScope', function ($scope, $location, $rootScope) {
$scope.msg=true;
$scope.trigger= function(data) {
if(data)
$scope.msg=false;
};
$rootScope.$on('event:fire', $scope.trigger);
}]);
// mainContent controller
module.controller('mainContent', ['$scope', '$location', 'dataService', function ($scope, $location, dataService) {
$scope.user = dataService.user;
$scope.signIn = function (user) {
var result = dataService.login(user);
result.success(function (data) {
if (data.message== "success") {
$rootScope.$broadcast('event:fire');
}
})
};
}]);
You can use $rootScope like:
<div ng-controller="header">
<p ng-show="$root.header.msg">Content</p>
</div>
<div ng-controller="mainContent">
</div>
var module = angular.module("sourceViewer", ['ui.router']);
//header controller
module.controller('header', function ($rootScope,$scope, $location) {
$rootScope.header.msg = true;
});
// mainContent controller
module.controller('mainContent', function ($rootScope,$scope, $location, dataService) {
$scope.user = dataService.user;
$scope.signIn = function (user) {
var result = dataService.login(user);
result.success(function (data) {
if (data.message== "success") {
$rootScope.header.msg = true;
}
})
};
});
in the follwoing code you can see headerController is calling alert in mainController
myApp = angular.module("myApp",[]);
myApp.service("myService", function(){
showAlertBool = false;
return {
showAlert: function (value) {
showAlertBool = value;
},
canShowAlert: function () {
return showAlertBool;
}
}
});
myApp.controller("headerController", function($scope, myService){
console.log(myService);
$scope.clickHandler = function(){
myService.showAlert(true);
}
});
myApp.controller("mainController", function($scope, myService){
console.log(myService);
$scope.getServiceValue = function(){
return myService.canShowAlert();
}
$scope.$watch("getServiceValue()", function(newValue, oldValue){
if(newValue === true && newValue !== oldValue){
myService.showAlert(false);
alert("I can show Alert now!!!");
}
});
});
For a working code you can go here