I am POSTing a form and I want to redirect to my list page in case the form has no errors/is successfully persisted/saved to the db. How do I achieve that ?
app.controller('NoteCreateController',
['$scope', 'Note', '$routeParams', '$location','ShareNoteScope',
function($scope, Note, $routeParams, $location, ShareNoteScope) {
$scope.notes = ShareNoteScope.getScope().notes;
$scope.newNote = {};
$scope.createNote = function(note) {
var newNote = new Note(note);
newNote.$save(function(newNote) {
$scope.notes.unshift(newNote.note);
$scope.note = '';
$scope.errors = '';
}, function(newNote) {
$scope.errors = newNote.data;
// $location.path('/notes/'+newNote.note.id); where do I put this?
});
}
}]);
$save wraps success call with a callback. The piece of code above should do the trick.
newNote.$save(function (newNote) {
//success callback
$location.path('/notes/' + newNote.note.id);
}, function (newNote) {
$scope.errors = newNote.data;
});
Related
I am very new to AngularJS.
I want to pass an array data from my app factory to app controller.
Here is my app.factory code.
App.factory('buyFactory', ['$http', function($http) {
factory.Search = function(scope, d) {
var data = scope.search;
scope.CarsData = [];
all_cars = [];
scope.isLoading = true;
$http.post(ajaxurl + '?action=search_car', d)
.success(function(response) {
angular.forEach(response, function(c) {
c.price = parseFloat(c.price);
c.driven = parseFloat(c.driven);
c.year = parseFloat(c.year);
});
angular.forEach(response, function(value, key) {
all_cars.push(value);
scope.CarsData = all_cars;
scope.TotalItems = scope.CarsData.length;
scope.isLoading = false;
})
.error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
scope.isLoading = false;
});
}
return factory;
}]);
and this is app.controller as
App.controller('buyController', ['$scope', '$http', 'buyFactory', '$filter', function($scope, $http, buyFactory, $filter) {
$scope.CarsScroll = buyFactory.Search.CarsData();
$scope.loadMore = function() {
var last = $scope.CarsScroll[$scope.CarsScroll.length - 1];
for (var i = 1; i <= 3; i++) {
$scope.CarsScroll.push(last + i);
}
};
//scroll
}]);
I want to use output obtained from factory i.e. CarsData as a variable in my app controller. But I am not able to get it. I have tried using services also. Is there method to use array data in a simplest way.
Your syntax is completely broken, i would recommend following any course of AngularJS. As for how to correctly do what you are trying to would look something like this
app.factory('buyFactory', ['$http', '$q', function($http, $q) {
var factory = {
search: function(d) {
return $q(function(resolve, reject) {
$http.post(ajaxurl + '?action=search_car', d).then(function(response) {
angular.forEach(response, function(c) {
c.price = parseFloat(c.price);
c.driven = parseFloat(c.driven);
c.year = parseFloat(c.year);
});
var carsData = [];
angular.forEach(response, function(value, key) {
carsData.push(value);
})
var result = {
carsData: carsData,
total: carsData.length
}
resolve(result);
}, function(error) {
reject(error);
})
});
}
}
return factory;
}]);
app.controller('buyController', ['$scope', '$http', 'buyFactory', '$filter', function($scope, $http, buyFactory, $filter) {
buyFactory.search().then(function(result) {
var cars = result.carsData;
var total = result.total;
})
}]);
Note: i do not know what the d parameter is for neither why the angular.forEach statements so it might not be fully functional. But this is more as guideline for how your factory should look and be used.
My code is as shown below:
angular.module('xyz.homeController', [])
.controller('homeController', ['homeService', '$scope', '$location', '$modal', '$rootScope', '$localstorage', '$window', 'GoogleSignin'
function(homeService, $scope, $location, $modal, $rootScope, $localstorage, $window, GoogleSignin) {
])
angular.module('xyz.homeService', [])
.factory('homeService', function() {
var data = {};
var deliveryOption = 0;
var payCardOption = 0;
var orderId = '';
var restaurentID = '';
var orderInfo = {};
var orderItems = [];
data.setDeliveryOption = function(info) {
this.deliveryOption = info;
};
data.getDeliveryOption = function() {
return this.deliveryOption;
};
data.setOrderId = function(orderId) {
this.orderId = orderId;
};
data.getOrderId = function() {
return this.orderId;
};
data.setRestaurentId = function(id) {
this.restaurentID = id;
};
data.getRestaurentID = function() {
return this.restaurentID;
};
data.setOrderInfo = function(info) {
this.orderInfo = info;
};
data.getOrderInfo = function() {
return this.orderInfo;
};
data.setOrderItems = function(items) {
this.orderItems = items;
};
data.getOrderItems = function() {
return this.orderItems;
};
data.setPayCardOption = function(payCardOption) {
this.payCardOption = payCardOption;
};
data.getPayCardOption = function() {
return this.payCardOption;
};
return data;
});
Now when refresh is pressed , the route is called perfectly, I have handlede the information inside the route perfectly, but somehow I am not able to restore the state of app and as a result of that, I am not able to use homeService perfectly, how to get the reference of homeService perfectly, so that I can use it?
The term you're looking for is singleton.
All services in AngularJs are singletons but you are using factory which is initialized by controller.
This will solve your problem if you're swithcing from one controller to the other.
However if you're refreshing the page, the application will reboot.
There's no way around it than using localstorage, sessionstorage, cookies...etc.
These are available through the $window service.
Hi I'm doing an application in Ionic Creator and I would like to retrieve one record from database that has given email address (userId) .
this is my code:
function ($scope, $stateParams, $firebaseArray, $ionicUser, $state, $ionicAuth) {
$scope.userData = $ionicUser.details;
$scope.data = {
'points': ''
}
$scope.logout = function(){
$ionicAuth.logout();
$state.go('tabsController.login');
};
var userId = $ionicUser.details.email;
var ref = firebase.database().ref().child('/users/' + userId);
$scope.users = $firebaseArray(ref);
}
but if my code is like that it works fine but display all the data from database:
function ($scope, $stateParams, $firebaseArray, $ionicUser, $state, $ionicAuth) {
$scope.userData = $ionicUser.details;
$scope.data = {
'points': ''
}
$scope.logout = function(){
$ionicAuth.logout();
$state.go('tabsController.login');
};
var ref = firebase.database().ref().child( "users");
// create a synchronized array
$scope.users = $firebaseArray(ref);
}
Any help would be super appreciated.
inject $firebaseObject into the controller and then do
var ref = firebase.database().ref().child('/users/');
$scope.user = $firebaseObject(ref.child(userId));
I am using karma- jasmine framework to test my angular application. I'm facing a problem in calling the functions of the controller or service form my test-spec. I tried using controller. as well as scope. but both of them didn't work for me.
The controller code is
(function () {'use strict';
angular.module('selfUi').controller('AttendeesController', AttendeesController);
AttendeesController.$inject = ['$state', '$stateParams', 'AttendeeService', 'settings', '$log'];
function AttendeesController($state, $stateParams, AttendeeService, settings, $log) {
var vm = this;
if ($stateParams.attendeeData === null) {
vm.pageType = "Add Attendee";
vm.isEdit = false;
} else {
var tempAttendee = $stateParams.attendeeData;
vm.pageType = "Edit Attendee";
vm.isEdit = true;
vm._id = tempAttendee._id;
vm.firstName = tempAttendee.firstName;
vm.lastName = tempAttendee.lastName;
}
vm.checkAvailable = function(email){
//Check email
if(email === null || angular.isUndefined(email) || email.trim().length === 0){
vm.invalidEmail = true;
}else{
// Check if email is already present or not
success = function(data, status, headers, config) {
if(data[0].success){
vm.validEmail = true;
}else{
if(data[0].message){
modalData = {
success : false,
};
}else{
vm.validEmail = false;
}
}
};
failure = function(data, status, headers, config) {
vm.invalidEmail = false;
};
AttendeeService.checkEmail(email, success, failure);
}
};
} })();
My test spec is:
describe('AttendeesController', function(){
beforeEach(module('SS'));
var state, $stateParams, stateParams, settings, AttendeeService, log;
var email= "temp#email.com";
var controller, $scope;
var vm;
$stateParams= {_id : "1",
attendeeType : "attendee",
firstName : "Pen",
lastName : "Red",
email : "temp#email.com",
company : "SWG",
jobTitle : "Speaker",
biography : "bio",
tagsInterest : "interests"}
beforeEach(inject(function($rootScope, _AddAttendeeService_, $controller, $state, $stateParams,settings, $log) {
AttendeeService= _AttendeeService_;
state= $state;
$scope = $rootScope.$new();
controller = function() {
return $controller('AttendeesController', {
$scope : scope,
$stateParams : $stateParams
});
};
}));
it('should be instantiated', function() {
expect(AttendeeService).toBeDefined();
});
it('should have controller.methods defined', function(){
expect(controller).toBeDefined();
expect(controller.checkAvailable).toBeUndefined();
controller.checkAvailable(email);
});
});
My service code looks like this:
(function() {
'use strict';
angular.module('SS').service('AttendeeService', AttendeeService);
AttendeeService.$inject = ['SSFactory', 'settings', '$rootScope'];
function AttendeeService(SelfSFactory, settings, $rootScope){
this.addAttendee = function(data, success, failure){
var responsePromise = SelfServiceFactory.httpPostRequest(settings.createAttendeeURL, data, config);
responsePromise.success(success);
responsePromise.error(failure);
return responsePromise;
};
}});
When I run my test spec, it gives me a error
TypeError: 'undefined' is not a function (evaluating 'controller.checkAvailable(email)')
at C:/Users/IBM_ADMIN/WebstormProjects/Self/self-service-ui.git/src/tests/addAttendees.controller.spec.js:53
I tried calling the checkAvailable function with the scope variable too, but it didn't work. I need to know how to call such methods in the controller from my test spec.
I'm an angular newbie and I'm writing an Ionic app.
I finished my app and am trying to refactor my controller avoiding code repetition.
I have this piece of code that manages my modal:
angular.module('starter')
.controller('NewsCtrl', function($scope, content, $cordovaSocialSharing, $timeout, $sce, $ionicModal){
$scope.news = content;
content.getList('comments').then(function (comments) {
$scope.comments = comments;
});
$scope.addComment = function() {
};
$scope.shareAnywhere = function() {
$cordovaSocialSharing.share("Guarda questo articolo pubblicato da DDay", "Ti stanno segnalando questo articolo", content.thumbnail, "http://blog.nraboy.com");
};
$ionicModal.fromTemplateUrl('templates/comments.html', {
scope: $scope,
animation: 'slide-in-up'
}).then(function(modal) {
$scope.modal = modal;
});
$scope.showComment = function() {
$scope.modal.show();
};
// Triggered in the login modal to close it
$scope.closeComment = function() {
$scope.modal.hide();
};
$scope.$on('modal.shown', function() {
var footerBar;
var scroller;
var txtInput;
$timeout(function() {
footerBar = document.body.querySelector('#commentView .bar-footer');
scroller = document.body.querySelector('#commentView .scroll-content');
txtInput = angular.element(footerBar.querySelector('textarea'));
}, 0);
$scope.$on('taResize', function(e, ta) {
if (!ta) return;
var taHeight = ta[0].offsetHeight;
if (!footerBar) return;
var newFooterHeight = taHeight + 10;
newFooterHeight = (newFooterHeight > 44) ? newFooterHeight : 44;
footerBar.style.height = newFooterHeight + 'px';
scroller.style.bottom = newFooterHeight + 'px';
});
});
});
I have added this same code in 6 controllers.
Is there a way to avoid the repetition?
Probably what you are looking for is an angular service. This component is a singleton object, that you inject in every controller you need to execute this code.
Angular Services
Regards,
Below is an example of a service I created to retrieve address data from a Json file. Here is the working Plunk. http://plnkr.co/edit/RRPv2p4ryQgDEcFqRHHz?p=preview
angular.module('myApp')
.factory('addressService', addressService);
addressService.$inject = ['$q', '$timeout', '$http'];
function addressService($q, $timeout, $http) {
var addresses = [];
//console.log("Number of table entries is: " + orders.length);
var promise = $http.get('address.data.json');
promise.then(function(response) {
addresses = response.data;
// console.log("Number of table entries is now: " + orders.length);
});
return {
GetAddresses: getAddresses
};
function getAddresses() {
return $q(function(resolve, reject) {
$timeout(function() {
resolve(addresses);
}, 2000);
});
}
}
Here's an example of how I added dependencies for it and another service to my controller (This is NOT the only way to do dependency injection, but is my favorite way as it is easier to read). I then called my addressService.GetAddresses() from within my controller.
var app = angular.module('myApp', ['smart-table']);
app.controller('TableController', TableController);
TableController.$inject = [ "orderService", "addressService"];
function TableController( orderService, addressService) {
addressService.GetAddresses()
.then(function(results) {
me.addresses = results;
// console.log(me.addresses.length + " addresses");
},
function(error) {})
.finally(function() {
me.loadingAddresses = false;
});
});}
I also had to include my .js tag in a script element on my index.html.
<script src="addressdata.service.js"></script>