AngularJS: use $broadcast to hide table columns - javascript

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();
}]);

Related

angularjs logged in user info to be available throughout the app

I want to make the user info available to all views after login. How can I modify the code to be able to access the pseudonym from the other view?
Can you please give an example?
Here is my login controller:
app.controller("MyregisterCtrl", ["$scope", "$stateParams", "Auth", "$state", "$location", "$modal", "DatabaseRef",
function ($scope, $stateParams, Auth, $state, $location, $modal, DatabaseRef) {
$scope.user = {};
$scope.signIn = function () {
if (!$scope.user.email && !$scope.user.password) {
toastr.error("Add email and password");
} else {
Auth.$signInWithEmailAndPassword($scope.user.email, $scope.user.password)
.then(function(firebaseUser) {
//=====user info=================
var userId = firebase.auth().currentUser.uid;
DatabaseRef.ref('/users/' + userId).once('value')
.then(function(snapshot) {
pseudonym = snapshot.val().pseudonym;
console.log("pseudonym: ", pseudonym);
return pseudonym;
});
//======================
$state.go('app.dashboard');
if (!firebaseUser.emailVerified) {
toastr.info('Your email is NOT verified.', 'Verify email!');
$state.go('login.signin');
}
})
.catch(function(error) {
toastr.error(error.message, error.reason, { timeOut: 10000 });
$scope.user = {};
})
}
};
}]);
this console.log("pseudonym: ", pseudonym); gives me what I want to access, but can't access it from other views, by just typing {{pseudonym}} for example.
Assign to a $scope variable, whenever you want to display on view ,
pseudonym = snapshot.val().pseudonym;
$scope.pseudonym =pseudonym;

Error: [$injector:unpr] Unknown provider: setPageProvider <- setPage

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 [];
}
});

Angular service is undefined

I'm trying to call the mergeUserList() function that is inside my service. I do this is my controller that looks like this:
app.controller('UserManagementController', ['$http','$sessionStorage','api','$modal','$scope','Session', 'divisionService','$filter', function ($http, $sessionStorage, api, $modal, $scope, $state, Session, divisionService,$filter) {
divisionService.mergeUserList().then(function(response)
{
$scope.users = response;
});
}]);
And my service:
app.factory("divisionService", function (api, $http, $q) {
//Organization divisions with division users
var division = {};
var divisionArray = [];
var mergedUserList = [];
return {
mergeUserList: function () {
if (divisionArray == null || divisionArray.length == 0) {
var list = [];
var d = $q.defer();
this.getList().then(function () {
divisionArray.forEach(function (y) {
y.users.forEach(function (user) {
list.push(user);
});
d.resolve(list);
})
});
return d.promise;
}
else {
return null;
}
}
};
return division;
});
My problem is that when i run the code it says TypeError: undefined is not a function in line 1 in the controller. I know for a fact that the problem is not in the service, becuase I use it in another controller, and there it works.
You have one $state as a function argument which is not included in the array, change it to:
app.controller('UserManagementController', ['$http','$sessionStorage','api','$modal','$scope', '$state', 'Session', 'divisionService','$filter', function ($http, $sessionStorage, api, $modal, $scope, $state, Session, divisionService, $filter) {

calling method from one controller to another controller in angular js

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

Good way to show messages and redirect in Angular

I have an angular application. In a controller I want to set a success or error message and then redirect to another route.
This should give you some idea of what I mean.
var myControllers= angular.module('myControllers', []);
myControllers.controller('SomeController', ['$scope', '$http', '$location',
function ($scope, $http, $location) {
$scope.doSomething = function () {
$http.get('/api/dosomething').then(function (result) {
if (result.data == 'true') {
$scope.successMessage = 'Yay it worked !!';
$location.path('/someotherroute');
}
else {
$scope.errorMessage = 'it did not work';
}
});
};
}
])
Does anyone have a nice solution for passing $scope.successMessage to the new controller ?
(i.e. the controller that is associated with '/someotherroute' )

Categories