I'm quite new with Angular and I am trying to bring some structure in my website I am building with Angular.
Now I have a Controller where I have some functions which I use on multiple pages. I have heard that I could better make a service out of these functions. How am I able to do this?
This is my Controller in current state:
How can I make a service from $scope.city function and $scope.specials function?
app.controller('DataCtrl', function($scope,$http){
$scope.city = function(){
$scope.items = [];
$http.get('/getdata').then(function(d){
$scope.items = d.data;
$scope.selectedItem = $scope.items[0];
},function(err){
console.log(err);
});
};
/* Function for specialization data */
$scope.specials = function(){
$scope.special = [];
$http.get('/specialdata').then(function(d){
$scope.special = d.data[0];
},function(err){
console.log(err);
});
};
});
Try like this
app.factory('getServiceData', function($http){
return {
getSpecials: function() {
return $http.get("/specialdata")
}
};
});
and for use it in controller inject factory or service into controller as you see in bellow.
app.controller('DataCtrl', function($scope,getServiceData){
getServiceData.getSpecials().then(function(response){
$scope.special = response.data[0];
})
};
Define a service, Here is an example
//Service.js
(function () {
angular.module('myApp')
.service('myService', service);
service.$inject = ['$http']
function service($http) {
this.specialdata = function () {
return $http.get('/specialdata')
}
}
})();
//Controller.js
(function () {
angular.module('myApp')
.controller('DataCtrl', DataCtrl);
DataCtrl.$inject = ['$scope', 'myService']
function DataCtrl($scope, myService) {
/* Function for specialization data */
$scope.specials = function () {
$scope.special = [];
myService.specialdata().then(function (d) {
$scope.special = d.data[0];
}, function (err) {
console.log(err);
});
};
}
})();
Related
In my factory..
var UserService = angular.module('UserService', []);
UserService.factory('UserApi', function ($http) {
var baseUrl = "http://localhost:59844/api";
var UserApi = {};
UserApi.getUsers = function () {
return $http.get(baseUrl + '/UserLogins');
};
});
And in my controller:
var myApp = angular.module('MyApp', ['ngRoute','UserService']);
myApp.controller('HomeController', function ($scope, UserApi) {
getUsers();
function getUsers(){
UserApi.getUsers.success(function (users) {
$scope.users = users;
}).error(function (error) {
$scope.status = "Couldn't load data";
})
}
});
It seems UserApi doesn't return any value. But cannot get it why?
You need to return the service object also
var UserService = angular.module('UserService', []);
UserService.factory('UserApi', function ($http) {
var baseUrl = "http://localhost:59844/api";
var UserApi = {};
UserApi.getUsers = function () {
return $http.get(baseUrl + '/UserLogins');
};
return UserApi;
});
I am trying to use the $http.get method to add a todo from my controller to my DB. But I am getting the error "TypeError: $scope.todos.push is not a function". I have looked at many similar questions to my own, and tried to implement the suggestions, with no success. The issue is in the $scope.createTodo function of the TodoController.
todo.controller.js
angular.module('app')
.controller('TodoController', ['$scope', 'Todos', function TodoController($scope, Todos) {
$scope.formData = {};
console.log("in the TodoController");
// when landing on the page, get all todos and show them
Todos.get()
.then(function (data){
$scope.todos = data;
}).then(function (error){
});
$scope.createTodo = function() {
if(!$scope.todoForm.$valid) {
return;
}
Todos.create($scope.formData)
.then(function (data){
$scope.formData = {};
$scope.todos.push(data);
}).then(function (error){
});
};
todo.service.js
angular.module('app')
.factory('Todos', ['$http', function($http) {
return {
get: function() {
return $http.get('/api/todos');
},
create: function(todoData) {
return $http.get('/api/todos', todoData).then(function (success){
},function (error){
});
},
delete: function(id) {
return $http.delete('/api/todos/' + id);
},
update: function(todoData) {
return $http.put('/api/todos/' + todoData.id, todoData);
}
}
}]);
To get rid from this kind of issue.
I simply first check not 'undefined' to perform any operation like push or length
if($scope.todos != undefined){
//to do here
} else {
console.log("$scope.todos is undefined");
}
//or
if($scope.todos !== 'undefined'){
//to do here
}
May help someone suffering with this tiny issue.
Because you did not declare $scope.todos so its return undefined and does not have push function, I think you have to declare your table before:
angular.module('app')
.controller('TodoController', ['$scope', 'Todos', function TodoController($scope, Todos) {
$scope.todos = [];
$scope.formData = {};
console.log("in the TodoController");
// when landing on the page, get all todos and show them
Todos.get()
.then(function (data){
$scope.todos = [data];
}).then(function (error){
});
$scope.createTodo = function() {
if(!$scope.todoForm.$valid) {
return;
}
Todos.create($scope.formData)
.then(function (data){
$scope.formData = {};
$scope.todos.push(data);
}).then(function (error){
});
};
Push works on array only, convert that model to an array your problem will be solved.
Hello evryone am having a problem with angular. I have a SPA the angular code is as it follows :
angular.module('myApp', ['ngResource']).controller('loginController',
['$scope', '$location', 'AuthService',
function ($scope, $location, AuthService) {
$scope.login = function () {
// initial values
$scope.error = false;
$scope.disabled = true;
// call login from service
AuthService.login($scope.loginForm.username, $scope.loginForm.password)
// handle success
.then(function () {
$location.path('/');
$scope.disabled = false;
$scope.loginForm = {};
})
// handle error
.catch(function () {
$scope.error = true;
$scope.errorMessage = "Invalid username and/or password";
$scope.disabled = false;
$scope.loginForm = {};
});
};
}]);
angular.module('myApp', ['ngResource']).controller('logoutController',
['$scope', '$location', 'AuthService',
function ($scope, $location, AuthService) {
$scope.logout = function () {
// call logout from service
AuthService.logout()
.then(function () {
$location.path('/login');
});
};
/*
$scope.posts = [];
$scope.newPost = {created_by: '', text: '', create_at: ''};
$scope.afficher = function(){
$scope.newPost.created_at = Date.now();
$scope.posts.push($scope.newPost);
$scope.newPost = {created_by: '', text: '', created_at: ''};
};
*/
/**
var Meetup = $resource('/api/meetups');
Meetup.query(function (results) {
$scope.meetups = results;
});
$scope.meetups = []
$scope.createMeetup = function () {
var meetup = new Meetup();
meetup.name = $scope.meetupName;
meetup.$save(function (result) {
$scope.meetups.push(result);
$scope.meetupName = '';
});
}
*/
}]);
angular.module('myApp', ['ngResource']).controller('registerController',
['$scope', '$location', 'AuthService',
function ($scope, $location, AuthService) {
$scope.register = function () {
// initial values
$scope.error = false;
$scope.disabled = true;
// call register from service
AuthService.register($scope.registerForm.username, $scope.registerForm.password)
// handle success
.then(function () {
$location.path('/login');
$scope.disabled = false;
$scope.registerForm = {};
})
// handle error
.catch(function () {
$scope.error = true;
$scope.errorMessage = "Something went wrong!";
$scope.disabled = false;
$scope.registerForm = {};
});
};
}]);
when my code is like this i get blank pages. but if i withdraw ['ngResource'] from the declaration off the app evrything works fine . can you help
// here you define the module with moduleName as 1st argument and dependencies as 2nd argument.
angular.module('myApp', ['ngResource']);
// When you call angular.module('myApp') with just the 1st argument (module name), it returns you the module already defined.
// here you declare a controller in the module already defined.
angular.module('myApp')
.controller('loginController',
['$scope', '$location', 'AuthService',
function ($scope, $location, AuthService) {
$scope.login = function () {
// initial values
$scope.error = false;
$scope.disabled = true;
// call login from service
AuthService.login($scope.loginForm.username, $scope.loginForm.password)
// handle success
.then(function () {
$location.path('/');
$scope.disabled = false;
$scope.loginForm = {};
})
// handle error
.catch(function () {
$scope.error = true;
$scope.errorMessage = "Invalid username and/or password";
$scope.disabled = false;
$scope.loginForm = {};
});
};
}]);
// here you declare another controller in the module already defined.
angular.module('myApp')
.controller('logoutController',
['$scope', '$location', 'AuthService',
function ($scope, $location, AuthService) {
$scope.logout = function () {
// call logout from service
AuthService.logout()
.then(function () {
$location.path('/login');
});
};
/*
$scope.posts = [];
$scope.newPost = {created_by: '', text: '', create_at: ''};
$scope.afficher = function(){
$scope.newPost.created_at = Date.now();
$scope.posts.push($scope.newPost);
$scope.newPost = {created_by: '', text: '', created_at: ''};
};
*/
/**
var Meetup = $resource('/api/meetups');
Meetup.query(function (results) {
$scope.meetups = results;
});
$scope.meetups = []
$scope.createMeetup = function () {
var meetup = new Meetup();
meetup.name = $scope.meetupName;
meetup.$save(function (result) {
$scope.meetups.push(result);
$scope.meetupName = '';
});
}
*/
}]);
// here you declare another controller in the module already defined.
angular.module('myApp')
.controller('registerController',
['$scope', '$location', 'AuthService',
function ($scope, $location, AuthService) {
$scope.register = function () {
// initial values
$scope.error = false;
$scope.disabled = true;
// call register from service
AuthService.register($scope.registerForm.username, $scope.registerForm.password)
// handle success
.then(function () {
$location.path('/login');
$scope.disabled = false;
$scope.registerForm = {};
})
// handle error
.catch(function () {
$scope.error = true;
$scope.errorMessage = "Something went wrong!";
$scope.disabled = false;
$scope.registerForm = {};
});
};
}]);
You can store the module reference in a variable and then use it further when defining controllers, services etc.
var myAppModule = angular.module('myApp', ['ngResource']);
myAppModule.controller('loginController',
['$scope', '$location', 'AuthService',
function ($scope, $location, AuthService) {
// Your code here
}]);
i try to make a getter and setter for the Supercontainer object, but it dose not seems to work.
PrometeiaECAProModuleMain.factory('ParameterFactory', [function () {
var Supercontainer = function (userId, supercontainerId, bankId) {
this.userId = userId;
this.supercontainerId = supercontainerid;
this.bankId = bankId;
};
return {
setSupercontainerParam: function (userId, supercontainerid, bank) {
supercontainer = new Supercontainer(userId, supercontainerid, bank);
},
getSupercontainerParam: function () {
return supercontainer;
}
};
}]);
I use it like this in my service.js
.factory('CommonService', function ($http, $state, Ls, md5, $filter) {
var headInfo = [];
return {
setData: function (key, data) {
headInfo[key] = data;
},
getData: function (key) {
return headInfo[key];
}
});
In the Controller you would set ur data like this
CommonService.setData('Dataname',{name:bla, price:25});
CommonService.getData('Dataname');
So I can pass all my data from one Controller to another and have it available everywhere
Service example. Can access the functions with ParameterFactory.getSupercontainer();
PrometeiaECAProModuleMain.service('ParameterFactory', function () {
var data = {};
this.setSupercontainer = function (userId, supercontainerId, bankId) {
data = {
'userId': userId,
'supercontainerId': supercontainerId,
'bankId': bankId
};
}
this.getSupercontainer = function () {
return data;
}
});
Hello I have this controller that handles login:
angular.module('fancyApp')
.controller('MainCtrl', function ($scope, $location, $http, LoginFactory) {
$scope.loginForm = function(isValid) {
if (isValid) {
var status;
LoginFactory.login($scope.person).then(function(d) {
console.log(d);
$scope.data = d;
if (d.status === 200) {
//login success
$('.loginFail').hide();
$location.path('/student');
} else {
$scope.loginFail = 'Failed to login';
$('.loginFail').show();
}
});
} else {
$scope.login_form.submitted = true;
}
};
});
And this is my LoginFactory login function:
angular.module('fancyApp')
.factory('LoginFactory', function ($http, $q) {
return {
login: function(user) {
var promise = $http.post( 'api/v1/login', user).then(function (response) {
return response;
}, function(error) {
return error;
});
return promise;
};
});
This is my beforeEach:
beforeEach(inject(function ($controller, $provide, $location, $rootScope) {
location = $location;
rootScope = $rootScope;
var testService = {
getStudents: function() {
return ['student1', 'student2'];
},
getAdmins: function() {
return ['admin1', 'admin2'];
},
login: function(person) {
console.log(testService.getStudents().indexOf(person.user));
if(testService.getStudents().indexOf(person.user) !== -1) {
return {status:200, token:'xxx', role:'student'};
}
else if(testService.getAdmins().indexOf(person.user) !== -1) {
return {status:200, token:'xxx', role:'admin'};
}
else {
return {status:401, token:'xxx', role:'student'};
}
}
};
scope = $rootScope.$new();
$provide.service('LoginService', testService);
MainCtrl = $controller('MainCtrl', {
$scope: scope
});
}));
And here is my test:
it('Login should succeed', inject(function($httpBackend){
spyOn(testService, 'login');
scope.person.user = 'student1';
scope.person.pass = '123456';
scope.login(true);
expect(testService.login).toHaveBeenCalledWith('student1', '123456');
}));
The error I get is:
Error: [$injector:unpr] Unknown provider: $provideProvider < $provide
I'm not sure if this is the correct way of testing this, any suggestions would be nice.
Thank you.
You can't use $provide within the inject function because the former registers providers for the latter to use. Do it like this:
describe('...', function() {
beforeEach(function() {
module(function($provide) {
$provide.service('LoginService', testService);
});
inject(function(someValue) {
//Rest of the code within the inject..........
});
});
});