angular.module('CrudApp', []).
config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/', {
templateUrl: 'assets/tpl/lists.html',
controller: ListCtrl
}).
when('/add-user', {
templateUrl: 'assets/tpl/add-new.html',
controller: AddCtrl
}).
otherwise({
redirectTo: '/'
});
}]);
function ListCtrl($scope, $http) {
$http.get('api/users').success(function(data) {
$scope.users = data;
});
}
function AddCtrl($scope, $http, $location) {
$scope.master = {};
$scope.activePath = null;
$scope.add_new = function(user, AddNewForm) {
console.log(user);
$http.post('api/add_user', user).success(function() {
$scope.reset();
$scope.activePath = $location.path('/');
});
$scope.deleteCustomer = function(customer) {
$location.path('/');
if (confirm("Are you sure to delete customer number: " + $scope.fld_Customer_Key) == true)
services.deleteCustomer(customer.customerNumber);
};
$scope.reset = function() {
$scope.user = angular.copy($scope.master);
};
$scope.reset();
};
}
// Delete user
I keep getting the error scope not defined and cannot seem to figure out why. can anybody help me troubleshoot this? All of the other functions are working except the delete customer. I don't know what is causing the error
Working Plunker
Here is it. I've updated your sintax, installed the dependencies and your $scope is working. Look at the Plunker. :)
Markup:
<body ng-app="CrudApp">
<div ng-controller="ListCtrl">
List Controller says what? {{what}}
</div>
<div ng-controller="AddCtrl">
Add Cntroller says What? {{what}}
</div>
</body>
script.js
var app = angular.module('CrudApp', ['ngRoute']);
app.controller('ListCtrl', function ($scope, $http) {
$scope.what = 'Rodrigo souza is beauty';
$http.get('api/users').success(function(data) {
$scope.users = data;
});
});
app.controller('AddCtrl', function ($scope, $http, $location) {
$scope.what = 'Rodrigo souza looks like Shrek';
$scope.master = {};
$scope.activePath = null;
$scope.add_new = function(user, AddNewForm) {
console.log(user);
$http.post('api/add_user', user).success(function() {
$scope.reset();
$scope.activePath = $location.path('/');
});
$scope.deleteCustomer = function(customer) {
$location.path('/');
if (confirm("Are you sure to delete customer number: " + $scope.fld_Customer_Key) == true)
services.deleteCustomer(customer.customerNumber);
};
$scope.reset = function() {
$scope.user = angular.copy($scope.master);
};
$scope.reset();
};
});
Working Plunker
Related
Here is my problem. Am new with angularjs and i want to get infos on the loggedin user. So i can for instance display it. I do not know how or where to start from here is my main angular controller.
var myApp = angular.module('myApp', ['ngResource', 'ngRoute']);
myApp.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'partials/main.html',
access: {restricted: true}
})
.when('/api/meetups', {
templateUrl: 'partials/main.html',
access: {restricted: true}
})
.when('/login', {
templateUrl: 'partials/login.html',
controller: 'loginController',
access: {restricted: false}
})
.when('/prive', {
templateUrl: 'partials/prive.html',
controller: 'userController',
access: {restricted: true}
})
.when('/logout', {
controller: 'logoutController',
access: {restricted: true}
})
.when('/register', {
templateUrl: 'partials/register.html',
controller: 'registerController',
access: {restricted: false}
})
.when('/one', {
template: '<h1>This is page one!</h1>',
access: {restricted: true}
})
.when('/two', {
template: '<h1>This is page two!</h1>',
access: {restricted: false}
})
.otherwise({
redirectTo: '/'
});
});
myApp.run(function ($rootScope, $location, $route, AuthService) {
$rootScope.$on('$routeChangeStart',
function (event, next, current) {
AuthService.getUserStatus()
.then(function(){
if (next.access.restricted && !AuthService.isLoggedIn()){
$location.path('/login');
$route.reload();
}
});
});
});
myApp.controller('meetupsController', ['$scope', '$resource', 'AuthService', function ($scope, $resource, AuthService) {
var Meetup = $resource('/api/meetups');
$scope.meetups = []
Meetup.query(function (results) {
$scope.meetups = results;
});
$scope.createMeetup = function () {
var meetup = new Meetup();
meetup.name = $scope.meetupName;
meetup.text = $scope.username;
meetup.$save(function (result) {
$scope.meetups.push(result);
$scope.meetupName = '';
$scope.username = '';
});
}
}]);
myApp.controller('userController', ['$scope', '$resource', function ($scope, $resource) {
/* var Meetup = $resource('/api/user');
$scope.users = []
Meetup.query(function (results) {
$scope.users = results;
});
*/
var Meetup = $resource('/api/user', {},{
query: {method: 'get', isArray: true}
});
$scope.users = []
$scope.text='mikyas';
Meetup.query({text: $scope.text}).$promise.then(function (results) {
$scope.users = results;
}, function(error) {
// console.log(error);
$scope.meetups = [];
});
}]);
Can anyone provide code please.
That is what a Service is for in Angular. Here is an example Authentication Service I am using in one of my Applications. If you want to keep a User logged in after closing the application you should also store the user in the local storage.
app.factory('AuthService', ['$q', '$http', 'LocalStorageService',
function($q, $http, LocalStorageService) {
var service = {};
service.user = LocalStorageService.get("AUTH_USER", null);
service.isLoggedIn = function(){
return service.user != null && service.user != undefined && service.user != "";
}
service.checkLogged = function(){
return $http.get(APPCONFIG.apiAccessPoint + "/user/" + service.user._id + "/isLogged").then(function(response){
if(!response.data.success || !response.data.logged){
service.logout();
return false;
}
else{
return true;
}
}, function(response){
service.logout();
return false;
});
}
service.login = function(name, password){
return $http.post(APPCONFIG.apiAccessPoint + "/user/login", {name: name, password: password}).then(function (response){
if(response.data.success){
LocalStorageService.set('AUTH_USER', response.data.data);
$http.defaults.headers.common.Authorization = 'Bearer ' + response.data.data.token;
service.user = response.data.data;
}
return response.data;
}, function (response){
if(response.status == 400 || response.data.error_code == "VAL_ERROR"){
return response.data;
}
else{
return $q.reject();
}
});
}
service.logout = function(){
// remove token from local storage and clear http auth header
LocalStorageService.deleteValue("AUTH_USER");
$http.defaults.headers.common.Authorization = '';
service.user = null;
}
return service;
}]);
And this is how you would use the service in a controller (for example showing a profile):
app.controller('ProfileViewCtrl', ['$scope', '$routeParams', 'AuthService', 'UserService',
function($scope, $routeParams, AuthService, UserService) {
$scope.isLogged = AuthService.isLoggedIn();
$scope.user = null;
$scope.notFound = false;
$scope.ownProfile = false;
$scope.user = UserService.getUser($routeParams.user).then(function(response){
if(response.success){
$scope.user = response.data;
$scope.notFound = response.data == undefined;
if(!$scope.notFound && $scope.isLogged){
$scope.ownProfile = $scope.user._id == AuthService.user._id;
}
}
else{
console.log(response.data);
}
});
}]);
Or with the login page:
app.controller('LoginCtrl', ['$scope', '$route', 'AuthService',
function($scope, $route, AuthService) {
$scope.user = {};
$scope.login = function(){
AuthService.login($scope.user.name, $scope.user.password).then(function(response){
if(response.success){
$route.reload();
}
else{
console.log("Wrong User or password...");
}
});
}
}]);
How do I include ui.bootstrap. I use ui.bootstrap to open the bootstrap modal(open) on ng-click. After that I want to send all modal data to server, for that I use $http in my angular controller. But it gives an error. Below is my angular js code.
var app = angular.module("modalFormApp", ['ui.bootstrap']);
app.controller("modalAccountFormController", ['$scope', '$modal', '$log', '$http'
function($scope, $modal, $log, $http) {
$scope.showForm = function() {
$scope.message = "Show Form Button Clicked";
console.log($scope.message);
var modalInstance = $modal.open({
templateUrl: 'modal-form.html',
controller: ModalInstanceCtrl,
scope: $scope,
resolve: {
userForm: function() {
return $scope.userForm;
}
}
});
modalInstance.result.then(function(selectedItem) {
$scope.selected = selectedItem;
}, function() {
$log.info('Modal dismissed at: ' + new Date());
});
};
}
]);
app.controller('ModalInstanceCtrl', ['$scope', '$http', '$modalInstance', userForm, function($scope, $http, $modalInstance, userForm) {
//var ModalInstanceCtrl = function ($scope, $modalInstance,$http, userForm) {
$scope.form = {}
$scope.url = 'submit.php';
$scope.submitForm = function() {
if ($scope.form.userForm.$valid) {
$http.post($scope.url, {
"name": $scope.name,
"email":
$scope.email,
"message": $scope.message
}).
success(function(data, status) {
console.log(data);
$scope.status = status;
$scope.data = data;
$scope.result = data;
})
} else {
console.log('userform is not in scope');
}
};
$scope.cancel = function() {
$modalInstance.dismiss('cancel');
};
}])
'ui.bootstrap' has prerequisites 'ngAnimate' and 'ngTouch'. You should add them to your module
var app = angular.module("modalFormApp", ['ngAnimate','ngTouch','ui.bootstrap']);
And you should add their scripts to your view
script(src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular-animate.min.js")
script(src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular-touch.min.js")
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 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
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");
});