I've searched and can't quite find someone with the same circumstances, I'm using angular routing to perform CRUD on a mock db.json server and when I execute the 'update' function, it changes the value in the database, but always redirects me to a blank page that just says 'Cannot POST /'. Even though the request actually went through. I'd just like it to return to the /clients page once the request is finished. I'm using browserify to include angular and angular-route. Thanks in advance :)
// Router
var UNRealtyApp = angular.module('UNRealtyApp', ['ngRoute'])
UNRealtyApp.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/clients', {templateUrl: 'app/views/clients.html', controller: 'clientListCtrl'})
.when('/add-client', {templateUrl: 'app/views/client-add.html', controller: 'clientAddCtrl'})
.when('/edit-client/:id', {templateUrl: 'app/views/client-edit.html', controller: 'clientEditCtrl'})
.otherwise({redirectTo: '/404'});
}]);
//Client CRUD
UNRealtyApp.controller('clientListCtrl', function ($scope, $http){
console.log('clientListCtrl activated')
$http.get('http://localhost:3000/clients/').success(function(data) {
$scope.clients = data;
})
})
UNRealtyApp.controller('clientAddCtrl', function ($scope, $http, $location){
console.log('clientAddCtrl activated')
$scope.master = {};
$scope.activePath = null;
$scope.add_new = function(client, AddNewForm) {
console.log('add_new activated')
$http.post('http://localhost:3000/clients/', client).success(function(){
$scope.reset();
$scope.activePath = $location.path('/clients');
});
$scope.reset = function() {
console.log('reset activated')
$scope.client = angular.copy($scope.master);
};
$scope.reset();
}
})
UNRealtyApp.controller('clientEditCtrl', function ($scope, $http, $location, $routeParams){
console.log('clientEditCtrl activated')
var id = $routeParams.id;
// $scope.activePath = null;
$http.get('http://localhost:3000/clients/' + id).success(function(data) {
$scope.clients = [data];
});
$scope.update = function(client){
console.log('update activated')
$http.put('http://localhost:3000/clients/' + id, client).success(function(data) {
$scope.clients = data;
$scope.activePath = $location.path('clients');
});
};
$scope.delete = function(client) {
console.log('delete activated')
var deleteClient = confirm('Are you sure you want to delete?');
if (deleteClient) {
$http.delete('http://localhost:3000/clients/' + client.id);
$scope.activePath = $location.path('clients');
}
}
})
Related
I can't figure out how to destroy my cache to get a new list from my server.
When I get the first list, it's work perfect, but after inserting informations to my database and sending another get to my server, the browser only show the cached version of my list, without the new data.
I tried to use cacheFactory like this:
$cacheFactory.get('$http').removeAll();
but it doesn't worked.
Here is my angular Module, Service and Controller.
Module myApp
var app = angular.module('myApp', ['ngRoute', 'LocalStorageModule', 'angular-loading-bar', 'smart-table']);
app.config(function ($routeProvider) {
$routeProvider.when("/home", {
controller: "homeController",
templateUrl: "/web/views/home.html"
});
$routeProvider.when("/cidades", {
controller: "cidadesController",
templateUrl: "/web/views/basico/cidades/cidades.html"
});
$routeProvider.otherwise({ redirectTo: "/home" });
});
app.config(function ($httpProvider) {
$httpProvider.interceptors.push('authInterceptorService');
});
app.run(['authService', function (authService) {
authService.fillAuthData();
}]);
cidadesService
'use strict';
app.factory('cidadesService', ['$http', '$cacheFactory', function ($http, $cacheFactory) {
var serviceBase = 'http://localhost:22207/';
var serviceFactory = {};
var _getCidades = function () {
$cacheFactory.get('$http').removeAll(); //This doesn't worked
return $http.get(serviceBase + 'api/cidades/getall').then(function (results) {
return results;
});
};
serviceFactory.getCidades = _getCidades;
return serviceFactory;
}]);
cidadesController
'use strict';
app.controller('cidadesController', ['$scope', 'cidadesService', function ($scope, service) {
$scope.cidade = {
id: "",
nome:"",
};
$scope.message = "";
$scope.getCidades = function () {
service.getCidades().then(function (results) {
$scope.cidades = [];
$scope.collection = [];
$scope.cidades = results.data;
$scope.collection = [].concat($scope.cidades);
}, function (err) {
$scope.message = err.error_description;
});
};
//Initializing the list
$scope.getCidades();
}]);
I really don't see anything wrong, but in any case you can add unique param for your request to prevent caching
like
$http.get(serviceBase + 'api/cidades/getall?unique=' + new Date().getTime())
I am trying to send an ID through to a controller using $routeParams via a factory but it is not working.
My $routeProvider:
.when('/event/:eventId', {
templateUrl : 'pages/event_detail.html',
controller : 'eventPageCtrl'
});
My factory:
myApp.factory('eventRepo', ['$http', function($http) {
var urlBase = 'php/api.php';
var eventRepo = {};
eventRepo.getEvent = function (id) {
return $http.get(urlBase + '?eventID=' + id);
};
return eventRepo;
}]);
My Controller:
myApp.controller('eventPageCtrl', ['$scope', '$routeParams', 'eventRepo',
function ($scope, $routeParams, eventRepo) {
$scope.getEvent = function (id) {
eventRepo.getEvent($routeParams.eventId)
.success(function (data) {
$scope.eventsDetail = data;
})
.error(function (error) {
$scope.status = 'Error retrieving event! ' + error.message;
});
};
}]);
When handling $http.get() inside the controller and not with the factory it works fine so I think I am not passing my $routeParams correctly? Perhaps this line is causing the issue eventRepo.getEvent($routeParams.eventId)?
This works currently, but trying to use $http.get() outside the controller:
myApp.controller('eventPageCtrl', function($scope, $http, $routeParams) {
$http.get("php/api.php?eventID="+$routeParams.eventId).success(function(data){
$scope.eventsDetail = data;
});
});
how about using resolve in your routeProver and returning the eventId and then injecting it in the controller .. example :
$routeProvider:
.when('/event/:eventId', {
templateUrl : 'pages/event_detail.html',
controller : 'eventPageCtrl',
resolve : {
eventId: function($route, $location) {
var eventId = $route.current.params.eventId;
return eventId;
});
Controller:
myApp.controller('eventPageCtrl', ['$scope', 'eventId', 'eventRepo',
function ($scope, eventId, eventRepo) { //add it as a dependency
$scope.eventId = eventId; //you can check this to see if its being assigned
$scope.getEvent = function (eventId) { //Edit: eventId added here
eventRepo.getEvent(eventId) //Edit: eventId passed
.success(function (data) {
$scope.eventsDetail = data;
})
.error(function (error) {
$scope.status = 'Error retrieving event! ' + error.message;
});
};
}]);
I would like to pass article id from url to factory but I can't get the value from $routeChangeSuccess callback.
myApp.controller('editCtrl', function($rootScope, $scope, getArticleById, $filter, $route, $routeParams) {
var article_id = $rootScope.$on('$routeChangeSuccess', function () {
return $routeParams.id;
});
getArticleById.get(article_id).then(function(data) {
$scope.articles = data;
});
});
myApp.factory('getArticleById', function($q, $http) {
return {
get: function(article_id) {
var deferred = $q.defer();
$http.get('/api/admin/article/edit/'+ article_id).success(function(result) {
deferred.resolve(result);
}).error(function(result) {
deferred.reject(result);
});
return deferred.promise;
}
}
});
$routeProvider
var myApp = angular.module('myApp',['ngRoute','ui.utils','ngSanitize','ui.tinymce'])
.config(function ($routeProvider, $locationProvider) {
//configure the routing rules here
$routeProvider.when('/admin/article/edit/:id', {
controller: 'editCtrl'
});
//routing DOESN'T work without html5Mode
$locationProvider.html5Mode(true);
}
);
Instead of creating a var named article_id in your controller, simply use the $routeParams.id to pass the value to factory.
getArticleById.get($routeParams.id).then(function(data) {
$scope.articles = data;
});
You can just update the articles in the $routeChangeSuccess callback.
myApp.controller('editCtrl', function($rootScope, $scope, getArticleById, $filter, $route, $routeParams) {
$rootScope.$on('$routeChangeSuccess', function () {
getArticleById.get($routeParams.id).then(function(data) {
$scope.articles = data;
});
});
});
This might cause problems when there is multiple route changes in quick successions. In which case you would need to do some more work.
I am creating a form with several input options for the end user, but with one input which I would like to be an UUID/GUID.
Here's what I have so far for the module (project.js):
angular.module('project', ['ngRoute', 'firebase'])
.value('fbURL', 'https://private.firebaseio.com/')
.factory('Projects', function($firebase, fbURL) {
return $firebase(new Firebase(fbURL));
})
.config(function($routeProvider) {
$routeProvider
.when('/', {
controller:'ListCtrl',
templateUrl:'list.html'
})
.when('/edit/:projectId', {
controller:'EditCtrl',
templateUrl:'detail.php'
})
.when('/new', {
controller:'CreateCtrl',
templateUrl:'detail.php'
})
.otherwise({
redirectTo:'/'
});
})
.controller('ListCtrl', function($scope, Projects) {
$scope.projects = Projects;
$scope.project = { trackid: 'UUID' };
})
.controller('CreateCtrl', function($scope, $location, $timeout, Projects) {
$scope.project = { trackid: 'UUID' };
$scope.save = function() {
Projects.$add($scope.project, function() {
$timeout(function() { $location.path('/'); });
});
};
})
.controller('EditCtrl',
function($scope, $location, $routeParams, $firebase, fbURL) {
var projectUrl = fbURL + $routeParams.projectId;
$scope.project = $firebase(new Firebase(projectUrl));
$scope.destroy = function() {
$scope.project.$remove();
$location.path('/');
};
$scope.save = function() {
$scope.project.$save();
$location.path('/');
};
$scope.project = { trackid: 'UUID' };
});
And here's what I have for the form input (in my detail.php file):
<form name="myForm">
<label>Track ID</label>
<input type="text" name="trackid" ng-model="project.trackid" disabled>
As you can tell, in this example I'm simply inserting the text "UUID" where I would actually like to insert an UUID. I can't however seem to figure out how to insert a function there that would be generating this UUID. Any help would be very much appreciated! Thank you!
If you have a function that returns the value needed you can simply do:
function getUUID(){
var result = /* parse value */
return result;
}
$scope.project ={ trackid: getUUID() };
DEMO
i am using one of the basic concept of angularjs that child controller inherit from parent controller. so i have writen the following code :
var editChannelCtrl = function ($scope, $route, $location, youtube) {
$scope.loading = false;
$scope.saved = false;
$scope.errors = [];
if (angular.isDefined($route.current.params.id)) {
$scope.isOldChannel = true;
$scope.isNewChannel = false;
} else {
$scope.isNewChannel = true;
$scope.isOldChannel = false;
}
};
editChannelCtrl.$inject = ['$scope', '$route', '$location', 'youtube'];
editChannelCtrl.resolve = {
channel: ['ServiceChannel' , function (ServiceChannel) {
return ServiceChannel.ChannelLoader();
}]
};
var oldChannelCtrl = function ($scope, $location, channel) {
$scope.channel = channel;
};
oldChannelCtrl.$inject = ['$scope' , '$location', 'channel'];
var newChannelCtrl = function ($scope, $location, Channel) {
$scope.channel = {
id: null,
version: 1
};
};
newChannelCtrl.$inject = ['$scope' , '$location', 'Channel'];
and for routes what i do , that i resolve the channel that load the channel for the edit form with the following code.
.when('/admin/refactor/channel/edit/:id', {
controller: editChannelCtrl,
templateUrl: '/admin/assets/views/channelForm.html',
resolve: editChannelCtrl.resolve
})
.when('/admin/refactor/channel/new', {
controller: editChannelCtrl,
templateUrl: '/admin/assets/views/channelForm.html'
})
but i don't know why angularjs don't figure how to inject channel to oldChannelCtrl ?