I am using $http service to call server that return json data.howerver each time i request for the json data , the $http service is executing multiple times.dont know what went wrong.plz help. thanks in advance.below is my code.
var app = angular.module('Demo',[]);
app.config(function ($routeProvider) {
$routeProvider
.when('/users',
{
templateUrl: "users.html",
controller: "users"
}
).when('/users/new',
{
templateUrl: 'new.html',
controller : 'newuser'
}).when('/users/:id/edit',
{
templateUrl: 'edit.html',
controller: 'edit'
})
});
app.controller('users',function($scope,$http){
$scope.list_of_users = [];
$http.get('http://testing.com:3000 /users.json').success(function(data,status,header,config){
angular.copy(data,$scope.list_of_users)
})
});
app.controller('newuser',function($scope,$http,$location){
$scope.done = function(){
var data = {user: {name: $scope.name}};
$http.post("http://testing.com:3000/users.json",data).success(function(data,status,header,config){
$location.path('/users');
}).error(function(data,stauts,header,confi){
});
};
});
app.controller('edit',function($scope,$http,$routeParams,$location){
$scope.name="";
$http.get("http://testing.com/users/"+$routeParams.id +".json").success(function(data,status,header,config){
console.log(data);
$scope.name = data['user']['name'];
});
$scope.update = function(){
var data = {user: {name: $scope.name}};
$http.put('http://localhost:3000/users/$routeParams.id',data).success(function(data,status,header,config){
$location.path("/users");
}).error(function(data,status,header,config){
});
}
});
Most likly you defined your controller in both the routeProvider and in the actuall template ( ng-controller ). This makes it run multiple times. Remove one of them and try again.
Related
I tried a lot and could not find proper answer which can solve my problem. Hope someone will help me out.
app.controller('MainController', ['$scope', 'MainService', 'CONSTANTS', '$routeParams', '$location',
function($scope, MainService, CONSTANTS, $routeParams, $location) {
$scope.indexAction = function() {
MainService.query({format: 'json'}, function(data){
$scope.data = data;
**This data still there when viewAction get call.**
});
}
$scope.newAction = function($event) {
$scope.isNew = true;
angular.isDefined($event)? $event.preventDefault() : false;
if(angular.isDefined($event)) {
var postData = $('#form').serialize();
MainService.save({format: 'json'}, postData, function(data, responseHeader){
var loc = responseHeader('location');
var r = /\d+/;
var dataId = loc.match(r);
$scope.viewAction(dataId[0]);
});
}
else {
$location.path('new');
}
}
$scope.viewAction = function(ObjOrId) {
var dataId = null;
if(angular.isObject(ObjOrId)) {
dataId = ObjOrId.id;
$scope.data = ObjOrId;
$location.path('view/'+dataId);
}
else {
dataId = ObjOrId;
MainService.get({Id: ObjOrId, format: 'json'}, function(data) {
$scope.data = data;
$location.path('view/'+dataId);
});
}
}
$scope.$on('ngRepeatFinished', function(ngRepeatFinishedEvent) {
});
}
]);
app.config(['$routeProvider', '$locationProvider',
function($routeProvider, $locationProvider) {
$routeProvider.
when('/new', {
templateUrl: 'abc.html',
controller: 'MainController'
}).
when('/view/:Id', {
templateUrl: 'xyz.html',
controller: 'MainController'
}).
otherwise({
templateUrl: 'list.html'
})
$locationProvider.html5Mode({
enabled: false
});
}
])
The data which comes in list.html with the help of indexAction that still exists when view route called and I am calling viewAction and loading data from ajax but that new data does not get updated in the view.
Please help!!
Your location.path looks like $location.path('new') when they should look like $location.path('/new');
Your other one looks like $location.path('view/'+dataId) when it should look like $location.path('/view'+ dataId);
I found the answer, I was using ng-model in form template and that was updating the $scope.data object without submitting the form itself, So i changed input directive ng-model to ng-value and while migrating to view template there i am able to get the data.
I am trying to use the code from here to show routes only when a promise is TRUE
I am following this for my directory structure
app
- Orders
-orders.html
-OrderController.js
-OrderService.js
Main-Config [app.js]
var myApp = angular.module('myApp', ['ngRoute','ngAnimate','ui.bootstrap','myApp.OrderController']);
myApp.config(function($routeProvider, $locationProvider){
$locationProvider.html5Mode({
enabled: true,
requireBase: false
});
$routeProvider
.when('/orders', {
templateUrl: 'orders/orders.html',
controller: 'OrderController',
resolve:{
customerExpenses: function(OrderService){
return OrderService.getOrders($route.current.params.customerName);
}
}
})
})
OrderService.js
angular.module('myApp').factory('OrderService', ['$http', function($http) {
var sdo = {
getNames: function() {
var promise = $http({
method: 'GET',
url: ''
});
promise.success(function(data, status, headers, conf) {
return data;
});
return promise;
}
}
return sdo;
}]);
I have tried the Accepted answer from here, and one of the suggestion from another SO article
angular.module('myApp')
.service('FooService', function(){
//...etc
})
.config(function(FooServiceProvider){
//...etc
});
As I have my service in a different file, I am trying to determine if I can use it in app.js file without using provider or is that the only way to use service in app.config?
UPDATE 1:
If i want to use the service in a controller
angular.module('myApp.OrderController',[]).controller('OrderController', function ($scope) {
$scope.displayed=[];
$scope.displayed.push(OrderService.getNames());
});
I get OrderService not available
Have tried this:
angular.module('myApp.OrderController',[]).controller('OrderController', ['$scope','OrderService',function ($scope) {
$scope.displayed=[];
$scope.displayed.push(OrderService.getNames());
}]);
followed example :
angular.
module('myServiceModule', []).
controller('MyController', ['$scope','notify', function ($scope, notify) {
$scope.callNotify = function(msg) {
notify(msg);
};
}]).
factory('notify', ['$window', function(win) {
var msgs = [];
return function(msg) {
msgs.push(msg);
if (msgs.length == 3) {
win.alert(msgs.join("\n"));
msgs = [];
}
};
}]);
but can not use my service. my controller and service are in different files
I added this question here as I feel they are somewaht related.
You have not injected your service OrderService, change your code in very first line
var myApp = angular.module('myApp', ['ngRoute','ngAnimate', ....'OrderService'])
myApp.config(function($routeProvider, $locationProvider, OrderService){
....
})
Rest of the code looks good
'use strict'
var hsbc = angular.module('hsbc',['ngResource','ngRoute']);
hsbc.config(['$routeProvider','$locationProvider', function ($routeProvider, $locationProvider){
//console.log('config part working');
$routeProvider
.when('/login', {
controller: 'hsbccontroller',
templateUrl: 'modules/authentication/views/login.html',
hideMenus: true
})
.when('/gloabltranfer', {
controller: 'hsbccontroller',
templateUrl: 'modules/home/views/gloabltranfer.html'
})
.when('/tranferReq', {
controller: 'hsbccontroller',
templateUrl: 'modules/home/views/TransferRquest.html'
})
.when('/reviewdetail', {
controller: 'hsbccontroller',
templateUrl: 'modules/home/views/Reviewdetails.html'
})
.when('/confirmdetail', {
controller: 'hsbccontroller',
templateUrl: 'modules/home/views/confirmdetails.html'
})
.when('/', {
templateUrl: 'modules/authentication/views/login.html'
})
.otherwise({ redirectTo: '/login' });
}]).controller('hsbccontroller', ['$scope','$http','$resource','$location', function($scope,$http,$resource,$location, transfer){
var gformcountry, gtocountry, userID, formData;
$scope.hsbcaccts = [];
$scope.countries = [];
$scope.login = function(){
var username = $scope.username;
var pass = $scope.password;
if(username =='test' && pass =='test'){
username = 1234;
$location.path('/gloabltranfer');
}
else if(username =='test2' && pass =='test2'){
username = 2222;
$location.path('/gloabltranfer');
}
else{
$location.path('/login');
}
}
$http.get('http://localhost/api/Accounts').success(function(data) {
$scope.hsbcaccts = data.body;
}).error(function(){
alert('Sorry server down at moment. please some time later');
});
$http.get('http://localhost/api/Country').success(function(data) {
$scope.countries = data.body;
}).error(function(){
alert('Sorry server down at moment. please some time later');
});
/*$http.get('json/currency.json').success(function(data) {
$scope.countries = data;
});*/
$scope.countryFromTo = function(){
$scope.fromData ={ 'fromcountry':$scope.fromcountry,'tocountry':$scope.tocountry};
$location.path('/tranferReq');
}
$scope.tranferForm = function(){
$scope.tranferForm ={ 'fromaccount':$scope.fromaccount,'toaccount':$scope.toaccount, };
return $scope.tranferForm;
$location.path('/reviewdetail');
}
$scope.reviewdetails = function(){
//alert($scope.tranferForm);
$location.path('/confirmdetail');
}
$http.get('http://localhost/api/Accounts').success(function(data){
//alert(data.id);
$scope.hsbcaccts = data;
});
}]);
Here getting data from ng-click tranferForm function without submitting data try binding to next page $scope tranferForm function collecting data and display in the page reviewdetail page.
and then my controller twice at a time.
First thing first, using same controllers in different pages means two different instances, completely independent of each other.
Now to share the variables between controllers,there are two ways to do this:
Store data in factories and fetch from the factories in other page.
But a parent controller at body level, or above the view node, and store the values in $scope variables of parent controller. Usually this is on the same html element as the ng-app and is supposed to be the parent of all the controllers.
Plus I think you should be using different controllers.
Putting same controller defeats the purpose of modular programming.
I don't know your case but if possible, create different controllers with different names and put only functions used per page in those controllers.
If there are some functions which are needed in all the places,create a generic function and put it in a service.
i am just learning basics of angular and today it started to change my app using a factory to get data and implementing route provider ! So far everything works fine! But when I try to add data on another view and head back to my list view scope is reloaded again from factory and no added data shows up.
My approach won't work because each time change my view I will call my controller which reloads data from factory! What can I do to make my Add template will work and changes data everywhere else too.
Maybe somebody can give me a tip how to cope with this problem ?
script.js
var app = angular.module('printTrips', ['ngRoute']);
app.factory('tripFactory', function($http) {
return{
getTrips : function() {
return $http({
url: 'trips.json',
method: 'GET'
})
}
}
});
app.controller('TripController', function($scope, $filter, tripFactory) {
$scope.trips = [];
tripFactory.getTrips().success(function(data){
$scope.trips=data;
var orderBy = $filter('orderBy');
$scope.order = function(predicate, reverse) {
$scope.trips = orderBy($scope.trips, predicate, reverse)};
$scope.addTrip = function(){
$scope.trips.push({'Startdate':$scope.newdate, DAYS: [{"DATE":$scope.newdate,"IATA":$scope.newiata,"DUTY":$scope.newduty}]})
$scope.order('Startdate',false)
$scope.newdate = ''
$scope.newiata = ''
$scope.newduty = ''
}
$scope.deleteTrip = function(index){
$scope.trips.splice(index, 1);
}
});
});
view.js
app.config(function ($routeProvider){
$routeProvider
.when('/',
{
controller: 'TripController',
templateUrl: 'view1.html'
})
.when('/view1',
{
controller: 'TripController',
templateUrl: 'view1.html'
})
.when('/view2',
{
controller: 'TripController',
templateUrl: 'view2.html'
})
.when('/addtrip',
{
controller: 'TripController',
templateUrl: 'add_trip.html'
})
.otherwise({ redirectTo: 'View1.html'});
});
Here is my plunker
Thanks for your help
You should use Service instead of Factory.
Services are loaded each time they are called. Factory are just loaded once.
app.service('tripFactory', function($http) {
return{
getTrips : function() {
return $http({
url: 'trips.json',
method: 'GET'
})
}
}
});
I have nested ui-views which are both waiting on data from http request. In the following code i have simulated this with timeouts. If i set the timeouts any longer than 10 ms then my plunker wont load at all.
var myapp = angular.module('myapp', ["ui.router"])
myapp.config(function($stateProvider, $urlRouterProvider){
// For any unmatched url, send to /route1
$urlRouterProvider.otherwise("/route1")
try{
$stateProvider
.state('contacts', {
templateUrl: 'contacts.html',
controller: function($scope, service1){
$scope.title = service1.getData()
}
,resolve:{
titlePromise:function(service1){
return service1.myPromise
}}
})
.state('contacts.list', {
templateUrl: 'contacts.list.html',
controller: function($scope, service2){
$scope.contacts = service2.getData();
},
resolve:{
contactPromise:function(service2){return service2.myPromise}
}
});
}catch(e){
alert.log(e);
}
});
The services are defined as follows.
myapp.factory('service1',['$q', function($q){
var title = 'Not Yet';
var _promise = $q.defer();
setTimeout(function(){
title='My Contacts';
_promise.resolve(true);
},100);
return {
getData:function(){return title},
myPromise: _promise.promise
}
}]);
myapp.factory('service2',['$q','service1', function($q, service1){
var data = [];
var _promise = $q.defer();
setTimeout(function(){
service1.myPromise.then(function(){
data=[{ name: 'Alice' }, { name: 'Bob' }];
_promise.resolve(true);
})
},100);
return{
getData:function(){return data},
myPromise:_promise
}
}]);
I need service2 to wait until service 1 returns its data in order to fulfill its request.The way I have it set up does not seem to work. What have I done wrong? If there is a better way to set up my app any suggestions are appreciated. I have modified the ui-view nested view demo plunker her: plnkr
Have a read of how hierarchical resolves work:
https://github.com/angular-ui/ui-router/wiki/Nested-States-%26-Nested-Views#wiki-what-do-child-states-inherit-from-parent-states
You don't need to wait for service 1 to complete inside service 2, but rather inject the results from the parent resolve into the child resolve function.