Im using angular service with a variable and my app.js looks like..,
app.service('sessionService', function() {
var users = [
name: ' ',
age: ' ',
gender: M,
marStatus: single
];
});
I have a logout option, how to reset my variable users to its default option?
You need to create a service with http call to your server action.The response will always set the data in a correct way.
var app = angular.module('myApp', []);
app.service('getUserDetailsService', ['$http', function($http) {
this.getDetails = function() {
var details = {name:'',age:'',gender:'M'}
$http.get('Your action url')
.success(function(data) {
details.name = data.name;
details.age = data.age;
details.gender = data.gender;
})
.error(function() {
//handle error
});
return details;
};
}]);
//Controller
app.controller("userController",function($scope,getUserDetailsService){
$scope.getDetails = function() {
getUserDetailsService.getDetails().then(function(detail) {
$scope.details = detail;
}, function(error) {
});
}
$scope.getDetails() //Call whenever you want
});
Fiddle link - https://jsfiddle.net/ftzyyt0L/3/
Related
I have a ASP.NET MVC web application.I am replacing a existing table control only (JQuery html coded) with AngularJS grid.
I want to pass id value to AngularJs app from jQuery click event. On click event below code is not working.Please suggest the right way to pass the value.Using angular.element is not working.
$(".bs-example").on('click', '#alldiv a', function () {
var id = $(this).attr("id");
// This id is required to use in angular app
angular.element($("#my-table")).scope().getData();
});
var myApp = angular.module('myGrid', ['ngTable']);
myApp.controller('gridCtrl', ['$scope', '$http', 'services', 'NgTableParams', function (scope, http, ser, NgTableParams) {
ser.getData().success(function (response) {
scope.agendas = response;
scope.tableParams = new NgTableParams({ page: 1, count: 2 }, { dataset: scope.mydata });
});
scope.mydata = {
data: 'mydata'
}
}]);
myApp.service('services', function ($http) {
this.getData = function () {
// Need id from button jQuery click event
var result = $http.get('/Home/GetData/' + id);
return result;
};
});
<div data-ng-app="myGrid" data-ng-controller="gridCtrl" id="my-table">
//.....
</div
This should work.
EDIT:
$(".bs-example").on('click', '#alldiv a', function () {
var id = $(this).attr("id");
//HEre you pass a id to angular controller.
angular.element($("#my-table")).scope().getData(id);
});
var myApp = angular.module('myGrid', ['ngTable']);
myApp.controller('gridCtrl', ['$scope', '$http', 'services', 'NgTableParams', function (scope, http, ser, NgTableParams) {
$scope.GetData = function(id) {
ser.getData(id).success(function (response) {
scope.agendas = response;
scope.tableParams = new NgTableParams({ page: 1, count: 2 }, { dataset: scope.mydata });
});
}
scope.mydata = {
data: 'mydata'
}
}]);
myApp.service('services', function ($http) {
//Add to this function parameter
this.getData = function (id) { //here declare that this function
// Need id from button jQuery click event
var result = $http.get('/Home/GetData/' + id);
return result;
};
});
IHMO better option here will be use a ng-click angular method on the div that you wana click.
https://docs.angularjs.org/api/ng/directive/ngClick
I am able to call Angular function from JQuery with following code
$(".bs-example").on('click', '#alldiv a', function () {
var id = $(this).attr("id");
var scope = angular.element(document.getElementById("my-table")).scope();
scope.$apply(function () {
scope.save(id);
});
});
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>
I have the following
Service:
angular.module('app')
.factory('UserFactory', function ($http) {
function profile () {
return $http.get('/gimme')
.then(function success (response) {
return response;
});
};
var user = {
profile: profile
};
return user;
It is used in a controller as follows:
Controller
angular.module('app')
.controller('HeaderCtrl', function ($scope, UserFactory) {
$scope.awesomeThings = [
'HTML5 Boilerplate',
'AngularJS',
'Karma'
];
$scope.user = UserFactory.profile().then(function (response) {
$scope.user = response.data;
});
$scope.change = function () {
$scope.user.name = 'New Name'
}
}
If I call the change() method in a directive which uses HeaderCtrl, what is the best way to make sure that that change, which temporarily changes the user.name, actually changes it on my server as well? In other words, how would I trigger the put request (I am assuming some function needs to be called on the Factory, but I am not sure the best way to make sure it is called or where to put the function call in the controller).
Thanks
Here's an example extending the code you provided, using free JSONPlaceholder API. I think example itself is enough of an answer?
HTML
<body ng-controller="Ctrl as vm">
<div>data: {{ vm.todo | json }}</div>
<div>response: {{ vm.response | json }} </div>
<hr>
<button type="button" ng-click="vm.change('my new title')">Change title</button>
</body>
JavaScript
app.controller('Ctrl', function(TodoService) {
var vm = this;
var id = 1;
TodoService.getPost(id).then(function(response) { // Get
vm.todo = response.data;
});
vm.change = function(val) {
vm.todo.title = val;
TodoService.putPost(vm.todo).then(function(response) { // Put
vm.response = response.status + ' ' + response.statusText;
}).catch(function(error) {
vm.response = angular.toJson(error);
});
};
});
app.factory('TodoService', function($http) {
var endpoint = 'http://jsonplaceholder.typicode.com/todos/';
var todoService = {};
todoService.getPost = function(id) {
return $http.get(endpoint + id).then(function(response) {
return response;
});
};
todoService.putPost = function(todo) {
return $http.put(endpoint + todo.id, todo).then(function(response) {
return response;
});
};
return todoService;
});
Related plunker here http://plnkr.co/edit/VBvVen
I'm very new to AngilarJS. I am trying to write a service in angularJS.
<script>
var module = angular.module("myapp", []);
module.service('BrandService', function ($http) {
var brands = [];
this.getBrands = function()
{
return $http.get('http://admin.localhost/cgi-bin/brand.pl')
.then(function(response)
{
brands = response.brands;
alert (brands);
});
}
//simply returns the brands list
this.list = function ()
{
return brands;
}
});
module.controller("brandsController", function($scope, BrandService) {
$scope.brandlist = BrandService.list();
alert ($scope.brandlist);
});
</script>
The statement "alert (brands);" is not getting called. What is the issue with this code. Is m missing any thing in implementation?
$http calls are always async. Meaning, even you do a .then at your service, there is no way it will properly the resolved data back into your controller. You will have to write it in your controller.
Your Service:
module.service('BrandService', function($http) {
var brands = [];
this.getBrands = function() {
//do not need the dot then.
return $http.get('http://admin.localhost/cgi-bin/brand.pl')
}
//simply returns the brands list
this.list = function() {
return brands;
}
});
In your controller:
module.controller("brandsController", function($scope, BrandService) {
BrandService.list()
.then(function(response) {
$scope.brandlist = response.brands;
alert($scope.brandlist);
});
});
In service:
this.getBrands = function() {
$http.get('http://admin.localhost/cgi-bin/brand.pl').then(function(response) {
brands = response.brands;
alert(brands);
return brands;
});
}
In controller:
$scope.brandlist = BrandService.getBrands();
alert($scope.brandlist);
Is it legal for a controller to do something like this in Angular?
$rootScope.someArbitaryObject = ["fee", "fie", "fo", "fum];
or
$rootScope.foo = {name: "Jane Q. Public", favoriteColor: "green"}
Yes, it is legal but only if you want ALL controllers to have access to that model.
A better practice is to use services that you can then inject to one or more controllers:
var myApp = angular.module('myApp', []);
myApp.factory('MyService', function () {
return { message: "I'm data from a service" };
});
myApp.controller('FirstCtrl', function($scope, MyService) {
$scope.data = MyService;
});
myApp.controller('SecondCtrl', function($scope, MyService) {
$scope.data = MyService;
});
Any change you make to MyService properties in one controller will affect all the other controllers that use MyService.
regarding the question in your comments, a good way to share date is through localstorage (or sessionStorage). I wrote a storageService which allows you to save, load and delete.
angular.module(yourApplication).service('storageService', [
function() {
// implementation using localStorage. Future possibility to user $cookie service here, or sessionStorage, depends on what you want
return {
save: function(key, jsonData, expirationMin){ // default is 30 minute expiration
if(!expirationMin)
expirationMin = 30;
var expirationMS = expirationMin * 60 * 1000;
var record = {
value: JSON.stringify(jsonData),
timestamp: new Date().getTime() + expirationMS
};
localStorage.setItem(key, JSON.stringify(record));
return jsonData;
},
load: function(key){
var record = JSON.parse(localStorage.getItem(key));
if (!record){
return false;
}
return (new Date().getTime() < record.timestamp && JSON.parse(record.value));
},
remove: function(key){
localStorage.removeItem(key);
}
};
}
]);
Another way using services (Modified Yoni's code a little):
var myApp = angular.module('myApp', []);
myApp.service('MyService', function () {
var someData = 'test';
return {
getData: function(){ return someData},
setData: function(input){ someData = input;}
};
});
myApp.controller('FirstCtrl', function($scope, MyService) {
$scope.data = MyService.getData();
});
myApp.controller('SecondCtrl', function($scope, MyService) {
$scope.data = MyService.getData;
});