AngularJS - Save data to $scope using routes? - angularjs

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'
})
}
}
});

Related

Using angularjs route how can I get a scope value into another controller?

I have project which is a single page application.So that I am using angular js route.
In the first controller I have a $scope value.The same value i have to use in the other controller
here is my controller.js file
var module = angular.module("sampleApp", ['ngRoute']);
module.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/route1', {
templateUrl: 'http://localhost/MyfirstApp/welcome',
controller: 'RouteController1'
}).
when('/route2', {
templateUrl: 'http://localhost/MyfirstApp/result',
controller: 'RouteController2'
}).
otherwise({
redirectTo: '/'
});
}]);
module.controller("RouteController1", function($scope)
{
$scope.value="Athira"
})
module.controller("RouteController2", function($scope) {
$scope.text=$scope.value + "Sandeep"
})
In the result page it should show as 'Athira Sandeep'
thank you for any kind of help
Use a service to share data among controllers .
Another option could be event emitters which i personally am not a fan because it populates the rootScope (in this case) with a lot of events.
What you could do it
angular.module('app',[])
.factory('SharedScope',function(){
var fac = this;
var scope = "";
var sharedScope = {
getScope : function(){
return fac.scope;
},
setScope: function(scope){
fac.scope = scope
}
};
return sharedScope;
})
.controller('Ctrl1',function('SharedScope'){
SharedScope.setScope("Angular");
})
.controller('Ctrl2',function('SharedScope'){
var data = SharedScope.getScope();
$scope.text = data + " is awesome"; //would get Angular is awesome
});
Hope this helps.

Ajax data via ngResource does not reflect after ngView update through ngRoute :(

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.

Ionic Framework no refresh list when navigate

I am creating a mobile app in AngularJS. I call a resource that calls an API to give me values. Everything works fine, but with slow connections or 3G $ scope not cool me, and therefore when browsing the list of items is old.
SERVICES.JS
.factory('Exercises', function($resource) {
// localhost: Local
// 79.148.230.240: server
return $resource('http://79.148.230.240:3000/wodapp/users/:idUser/exercises/:idExercise', {
idUser: '55357c898aa778b657adafb4',
idExercise: '#_id'
}, {
update: {
method: 'PUT'
}
});
});
CONTROLLERS
.controller('ExerciseController', function($q, $scope, $state, Exercises) {
// reload exercises every time when we enter in the controller
Exercises.query(function(data) {
$scope.exercises = data;
});
// refresh the list of exercises
$scope.doRefresh = function() {
// reload exercises
Exercises.query().$promise.then(function(data) {
$scope.exercises = data;
}, function(error) {
console.log('error');
});
// control refresh element
$scope.$broadcast('scroll.refreshComplete');
$scope.$apply();
}
// create a new execersie template
$scope.newExercise = function() {
$state.go('newExercise');
};
// delete a exercise
$scope.deleteExercise = function(i) {
// we access to the element using index param
var exerciseDelete = $scope.exercises[i];
// delete exercise calling Rest API and later remove to the scope
exerciseDelete.$delete(function() {
$scope.exercises.splice(i, 1);
});
};
})
APP.js
angular.module('wodapp', ['ionic', 'ngResource', 'wodapp.controllers','wodapp.services'])
// Run
.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
// ionic is loaded
});
})
// Config
.config(function($stateProvider, $urlRouterProvider, $ionicConfigProvider) {
$stateProvider
.state('slide', {
url: '/',
templateUrl: 'templates/slides.html',
controller: 'SlideController'
})
.state('login', {
url: '/login',
templateUrl: 'templates/login.html',
controller: 'LoginController'
})
.state('dashboard', {
url: '/dashboard',
templateUrl: 'templates/dashboard.html',
controller: 'DashboardController'
})
.state('exercise', {
url: '/exercise',
templateUrl: 'templates/exercises.html',
controller: 'ExerciseController'
})
.state('newExercise',{
url: '/newExercise',
templateUrl: 'templates/newExercise.html',
controller: 'NewExerciseController'
});
$urlRouterProvider.otherwise('/');
});
If you want to reload a part of your controller logic, every time the view is activated:
.controller('ExerciseController', function(
$q,
$scope,
$state,
Exercises,
$ionicView
) {
// reload exercises every time when we enter in the controller
$ionicView.enter(function(){
// This gets executed regardless of ionicCache
Exercises.query(function(data) {
$scope.exercises = data;
});;
});
});
Else, you can use the reload option on .state()

$http service executing multiple times in controller

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.

AngularJS+ Firebase can't get data preloaded on route change

var testApp = angular.module('testApp', ['firebase'])
.config(['$routeProvider','$locationProvider',function
($routeProvider,$locationProvider)
{
$routeProvider
.when('/', {
templateUrl: '/views/main.html',
controller: 'MainCtrl'
})
.when('/test', {
templateUrl: '/views/test.html',
controller: testCrtl,
resolve:
{
firedata: function($q,angularFire){
var deffered = $q.defer();
var ref = new Firebase('https://shadowfax.firebaseio.com/items');
ref.on('value', function(result){
deffered.resolve(result.val());
});
return deffered.promise;
}
}
})
.otherwise({
redirectTo: '/'
});
// $locationProvider.html5Mode( true );
}]);
angular.module('testApp')
.controller('MainCtrl', ['$scope','$routeParams','$rootScope', function ($scope,$routeParams,$rootScope) {
$scope.load = function(){ return false;}
$rootScope.$on('$routeChangeStart', function(next, current) {
$scope.load = function(){ return true;}
});
}]);
testApp.controller('TestCtrl',['$scope','$timeout','Fire','firedata','testCrtl']);
var testCrtl = function ($scope,$timeout,Fire,firedata) {
$scope.items=firedata;
};
In the code above, why is the value of $scope.items=firedata; null? Please explain how can I perform a Google-like route change to preload data for the controller? This example works like John Lindquist explains, but when I use Firebase's native JS library, I can't get the data preloaded.
Also, using the Firebase angularFire library doesn't help, because it uses $scope as a parameter and it's not possible to pass $scope to the resolve function.
You should be able to use angularFireCollection to preload data:
.when('/test', {
templateUrl: '/views/test.html',
controller: testCrtl,
resolve: {
firedata: function(angularFireCollection){
return angularFireCollection('https://shadowfax.firebaseio.com/items');
}
}
})

Resources