AngularJS/Angularfire Unable to splice object - javascript

When trying to remove an object using splice I get an error: TypeError: Object # has no method 'splice'
result of console.log($scope.posts[$routeParams.id]);
Object {name: "test", url: "http://google.com", $$hashKey: "005"}
my add and edit functions both work as expected. remove is similar, so I expect it to work as well.
controllers.js
/* Controllers */
hackerNews.controller('AppCtrl',
function AppCtrl ($scope, posts, angularFire) {
angularFire(posts.limit(100), $scope, 'posts');
});
hackerNews.controller('InfoCtrl',
function InfoCtrl($scope, $routeParams) {
$scope.post = $scope.posts[$routeParams.id];
});
hackerNews.controller('AddCtrl',
function AddCtrl($scope, $location, posts) {
$scope.post = [{}];
$scope.add = function () {
posts.push($scope.post);
$location.url('/');
};
});
hackerNews.controller('EditCtrl',
function EditCtrl($scope, $routeParams, $location, posts) {
$scope.post = $scope.posts[$routeParams.id];
$scope.edit = function () {
$scope.posts[$routeParams.id] = $scope.post;
$location.url('/');
};
});
hackerNews.controller('RemoveCtrl',
function RemoveCtrl($scope, $routeParams, $location, posts) {
$scope.post = $scope.posts[$routeParams.id];
$scope.remove = function () {
console.log($scope.posts[$routeParams.id]);
$scope.posts.splice($routeParams.id, 1);
$scope.toRemove = null;
$location.url('/');
};
$scope.back = function () {
$location.url('/');
};
});
app.js
/* Declare app level module */
var hackerNews = angular.module('hackerNews', ['firebase'])
.factory('posts', [function() {
var posts = new Firebase('https://xyclos.firebaseio.com/hackerNews');
return posts;
}])
.config(function($routeProvider) {
$routeProvider.when('/index', {
templateUrl: 'partials/index.html'
})
.when('/info/:id', {
templateUrl: 'partials/info.html',
controller: 'InfoCtrl'
})
.when('/add', {
templateUrl: 'partials/add.html',
controller: 'AddCtrl'
})
.when('/edit/:id', {
templateUrl: 'partials/edit.html',
controller: 'EditCtrl'
})
.when('/remove/:id', {
templateUrl: 'partials/remove.html',
controller: 'RemoveCtrl'
})
.when('/comments/:id', {
templateUrl: 'partials/comments.html',
controller: 'CommentCtrl'
})
.otherwise({
redirectTo: '/index'
});
});
hackerNews.filter('shortURL', function () {
return function (text) {
var getLocation = function(href) {
var l = document.createElement("a");
l.href = href;
return l;
};
var url = getLocation(text);
return url.hostname;
};
});
remove.html
<p>Are you sure that you want to remove {{post.name}}?</p>
<button ng-click="remove()" class="btn btn-success btn-sm">Yes</button>
<button ng-click="back()" class="btn btn-danger btn-sm">No</button>

I got it to work, even though I am not sure if this is necessarily the best way to do this.
here is what I changed:
remove.html
<button **ng-click="posts.remove(post)"** class="btn btn-success btn-sm">Yes</button>
after that, there was no need for me to do anything in remove() except route back to index
$scope.remove = function () {
$location.url('/');
};

Related

I would like to get the loggedin user info

Here is my problem. Am new with angularjs and i want to get infos on the loggedin user. So i can for instance display it. I do not know how or where to start from here is my main angular controller.
var myApp = angular.module('myApp', ['ngResource', 'ngRoute']);
myApp.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'partials/main.html',
access: {restricted: true}
})
.when('/api/meetups', {
templateUrl: 'partials/main.html',
access: {restricted: true}
})
.when('/login', {
templateUrl: 'partials/login.html',
controller: 'loginController',
access: {restricted: false}
})
.when('/prive', {
templateUrl: 'partials/prive.html',
controller: 'userController',
access: {restricted: true}
})
.when('/logout', {
controller: 'logoutController',
access: {restricted: true}
})
.when('/register', {
templateUrl: 'partials/register.html',
controller: 'registerController',
access: {restricted: false}
})
.when('/one', {
template: '<h1>This is page one!</h1>',
access: {restricted: true}
})
.when('/two', {
template: '<h1>This is page two!</h1>',
access: {restricted: false}
})
.otherwise({
redirectTo: '/'
});
});
myApp.run(function ($rootScope, $location, $route, AuthService) {
$rootScope.$on('$routeChangeStart',
function (event, next, current) {
AuthService.getUserStatus()
.then(function(){
if (next.access.restricted && !AuthService.isLoggedIn()){
$location.path('/login');
$route.reload();
}
});
});
});
myApp.controller('meetupsController', ['$scope', '$resource', 'AuthService', function ($scope, $resource, AuthService) {
var Meetup = $resource('/api/meetups');
$scope.meetups = []
Meetup.query(function (results) {
$scope.meetups = results;
});
$scope.createMeetup = function () {
var meetup = new Meetup();
meetup.name = $scope.meetupName;
meetup.text = $scope.username;
meetup.$save(function (result) {
$scope.meetups.push(result);
$scope.meetupName = '';
$scope.username = '';
});
}
}]);
myApp.controller('userController', ['$scope', '$resource', function ($scope, $resource) {
/* var Meetup = $resource('/api/user');
$scope.users = []
Meetup.query(function (results) {
$scope.users = results;
});
*/
var Meetup = $resource('/api/user', {},{
query: {method: 'get', isArray: true}
});
$scope.users = []
$scope.text='mikyas';
Meetup.query({text: $scope.text}).$promise.then(function (results) {
$scope.users = results;
}, function(error) {
// console.log(error);
$scope.meetups = [];
});
}]);
Can anyone provide code please.
That is what a Service is for in Angular. Here is an example Authentication Service I am using in one of my Applications. If you want to keep a User logged in after closing the application you should also store the user in the local storage.
app.factory('AuthService', ['$q', '$http', 'LocalStorageService',
function($q, $http, LocalStorageService) {
var service = {};
service.user = LocalStorageService.get("AUTH_USER", null);
service.isLoggedIn = function(){
return service.user != null && service.user != undefined && service.user != "";
}
service.checkLogged = function(){
return $http.get(APPCONFIG.apiAccessPoint + "/user/" + service.user._id + "/isLogged").then(function(response){
if(!response.data.success || !response.data.logged){
service.logout();
return false;
}
else{
return true;
}
}, function(response){
service.logout();
return false;
});
}
service.login = function(name, password){
return $http.post(APPCONFIG.apiAccessPoint + "/user/login", {name: name, password: password}).then(function (response){
if(response.data.success){
LocalStorageService.set('AUTH_USER', response.data.data);
$http.defaults.headers.common.Authorization = 'Bearer ' + response.data.data.token;
service.user = response.data.data;
}
return response.data;
}, function (response){
if(response.status == 400 || response.data.error_code == "VAL_ERROR"){
return response.data;
}
else{
return $q.reject();
}
});
}
service.logout = function(){
// remove token from local storage and clear http auth header
LocalStorageService.deleteValue("AUTH_USER");
$http.defaults.headers.common.Authorization = '';
service.user = null;
}
return service;
}]);
And this is how you would use the service in a controller (for example showing a profile):
app.controller('ProfileViewCtrl', ['$scope', '$routeParams', 'AuthService', 'UserService',
function($scope, $routeParams, AuthService, UserService) {
$scope.isLogged = AuthService.isLoggedIn();
$scope.user = null;
$scope.notFound = false;
$scope.ownProfile = false;
$scope.user = UserService.getUser($routeParams.user).then(function(response){
if(response.success){
$scope.user = response.data;
$scope.notFound = response.data == undefined;
if(!$scope.notFound && $scope.isLogged){
$scope.ownProfile = $scope.user._id == AuthService.user._id;
}
}
else{
console.log(response.data);
}
});
}]);
Or with the login page:
app.controller('LoginCtrl', ['$scope', '$route', 'AuthService',
function($scope, $route, AuthService) {
$scope.user = {};
$scope.login = function(){
AuthService.login($scope.user.name, $scope.user.password).then(function(response){
if(response.success){
$route.reload();
}
else{
console.log("Wrong User or password...");
}
});
}
}]);

angular $broadcast event is not firing?

I want to send data from parent to child controller but its not firing event from parent controller its been hours i am scratching my head find the problem but i failed so decided to ask help on stackoverflow, Any idea what is wrong in below code ?
ParentCtrl.js
angular.module('angularModelerApp')
.controller('ModelerCtrl', ['$scope', '$state','$log', 'toastr', 'FileSaver', 'Blob', '$uibModal', '$rootScope', '$timeout', function($scope, $state, $log, toastr, FileSaver, Blob, $uibModal, $rootScope, $timeout) {
$scope.deleteXml = function(id, toast) {
var id = $scope.diagramObj._id;
$scope.modalInstance = $uibModal.open({
templateUrl: 'app/modeler/modelerDialog/modelerDialog.html',
controller: 'ModelerDialogCtrl'
});
$timeout(function() {
$rootScope.$broadcast('delete-diagram', {
id: id
});
});
}
});
childCtrl.js
angular.module('angularModelerApp')
.controller('ModelerDialogCtrl', function ($scope, $uibModalInstance,$log,diagramService,$rootScope) {
$scope.cancel = function() {
$uibModalInstance.dismiss('cancel');
};
$scope.$on('delete-diagram',function(e,data){
console.log('in $on',data);
});
Why dont you pass the id when you open the modal such as:
$scope.modalInstance = $uibModal.open({
templateUrl: 'app/modeler/modelerDialog/modelerDialog.html',
controller: 'ModelerDialogCtrl',
resolve: {
item: function() {
return $scope.diagramObj._id
}
}
});
Fetch it in the child component in this way:
angular.module('angularModelerApp')
.controller('ModelerDialogCtrl', function ($scope, $uibModalInstance,$log,diagramService,$rootScope) {
$scope.cancel = function() {
$uibModalInstance.dismiss('cancel');
};
$scope.$on('delete-diagram',function(e,data){
console.log('in $on',data);
});
$uibModalInstance.result.then(function (data) {
console.log(data);
})
}

Scope not defined

angular.module('CrudApp', []).
config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/', {
templateUrl: 'assets/tpl/lists.html',
controller: ListCtrl
}).
when('/add-user', {
templateUrl: 'assets/tpl/add-new.html',
controller: AddCtrl
}).
otherwise({
redirectTo: '/'
});
}]);
function ListCtrl($scope, $http) {
$http.get('api/users').success(function(data) {
$scope.users = data;
});
}
function AddCtrl($scope, $http, $location) {
$scope.master = {};
$scope.activePath = null;
$scope.add_new = function(user, AddNewForm) {
console.log(user);
$http.post('api/add_user', user).success(function() {
$scope.reset();
$scope.activePath = $location.path('/');
});
$scope.deleteCustomer = function(customer) {
$location.path('/');
if (confirm("Are you sure to delete customer number: " + $scope.fld_Customer_Key) == true)
services.deleteCustomer(customer.customerNumber);
};
$scope.reset = function() {
$scope.user = angular.copy($scope.master);
};
$scope.reset();
};
}
// Delete user
I keep getting the error scope not defined and cannot seem to figure out why. can anybody help me troubleshoot this? All of the other functions are working except the delete customer. I don't know what is causing the error
Working Plunker
Here is it. I've updated your sintax, installed the dependencies and your $scope is working. Look at the Plunker. :)
Markup:
<body ng-app="CrudApp">
<div ng-controller="ListCtrl">
List Controller says what? {{what}}
</div>
<div ng-controller="AddCtrl">
Add Cntroller says What? {{what}}
</div>
</body>
script.js
var app = angular.module('CrudApp', ['ngRoute']);
app.controller('ListCtrl', function ($scope, $http) {
$scope.what = 'Rodrigo souza is beauty';
$http.get('api/users').success(function(data) {
$scope.users = data;
});
});
app.controller('AddCtrl', function ($scope, $http, $location) {
$scope.what = 'Rodrigo souza looks like Shrek';
$scope.master = {};
$scope.activePath = null;
$scope.add_new = function(user, AddNewForm) {
console.log(user);
$http.post('api/add_user', user).success(function() {
$scope.reset();
$scope.activePath = $location.path('/');
});
$scope.deleteCustomer = function(customer) {
$location.path('/');
if (confirm("Are you sure to delete customer number: " + $scope.fld_Customer_Key) == true)
services.deleteCustomer(customer.customerNumber);
};
$scope.reset = function() {
$scope.user = angular.copy($scope.master);
};
$scope.reset();
};
});
Working Plunker

Getting no response from $scope in angularjs

This is my method for getting a single user. The console.log prints the right object, but in when i try to access the $scope.user in the HTML I get no response, the tags are empty:
$scope.getByUsername = function (id) {
return $http.get('/api/User/' + id).success(function (data) {
$scope.user = data;
console.log($scope.user);
});
}
HTML:
<input type="text" name="name" ng-model="user.Username" />
<button ng-click="getByUsername(user.Username)">Button</button>
<h4>{{user.Username}}</h4>
<h4>{{user.Name}}</h4>
<h4>{{user.ImageLink}}</h4>
Edit:
var BlogFeedApp = angular.module('blogFeedApp', ['ngRoute', 'ngResource']).
config(['$routeProvider', function ($routeProvider) {
$routeProvider.
when('/', { controller: MainController, templateUrl: 'posts.html' }).
when('/test', { controller: MainController, templateUrl: 'test.html' }).
when('/new-post', { controller: PostController, templateUrl: 'new-post.html' }).
when('/new-user', { controller: UserController, templateUrl: 'new-user.html' }).
otherwise({ redirectTo: '/' });
}]);
Try removing the return keyword on line 2 of your JS.
Use something like following :
$scope.getByUsername = function (id) {
return $http.get('/api/User/' + id).success(function (data) {
$scope.user = data;
console.log($scope.user);
return data;
});
}
This should do the trick.
I think it is because your user is not defined when angularjs bootstrap. Can you try define user outside of $http callback?
$scope.user = {};
$scope.user.Username = "";
$scope.getByUsername = function (id) {
return $http.get('/api/User/' + id).success(function (data) {
$scope.user = data;
console.log($scope.user);
return data;
});
}

Angular.js - making function available in other controllers

I have an angular controller called SubmissionTreeController and it has update_dashboard() function which refreshes the ui every minute.
My goal is to refresh the ui on successful post request from a different controller.
How do I make this function available in other controllers?
var module = angular.module("submissionDashboard", ['ui.tree', 'ngCookies', 'ui.bootstrap',]);
module.controller("SubmissionTreeController", ["$scope", "$http", "$modal",
function($scope, $http, $modal) {
$scope.selected_items = {};
var update_dashboard = function() {
var url = Django.url('submission:active_list_ajax', {
site : site
});
$http.get(url).success(function(data) {
$scope.list = data.results;
});
};
update_dashboard();
$scope.closeTask = function(scope) {
var modalInstance = $modal.open({
templateUrl: 'modal_close_submission_renderer.html',
controller: 'ModalCloseSubmissionController',
resolve: {
items: function () {
return $scope.selected_items;
}}
});
};
}]);
module.controller('ModalCloseSubmissionController', ['$scope', '$modalInstance', '$http', 'items', function ($scope, $modalInstance, $http, items) {
$scope.items = items;
$scope.selected = {
item: 1,
text: ''
};
$scope.ok = function () {
var val = $scope.selected.item;
if (val === 1) {
var url = Django.url('submission:close-notify', {
site : site
});
$http.post(url, $scope.selected_items).success(function(data) {
update_dashboard();
});
} else if (val === 2) {
var url = Django.url('submission:close', {
site : site
});
$http.post(url, $scope.selected_items).success(function(data) {
update_dashboard();
});
} else if (val === 3) {
var url = Django.url('submission:cancel', {
site : site
});
$http.post(url, $scope.selected_items).success(function(data) {
update_dashboard();
});
};
$modalInstance.close($scope.selected.item);
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
}]);
Edit:
What I am trying to do:
module.service('updateDashboardService', function($scope, $http){
this.update_dashboard = function() {
$scope = $scope;
var url = Django.url('submission:active_list_ajax', {
site : site
});
$http.get(url).success(function(data) {
$scope.list = data.results;
});
};
});
module.controller("SubmissionTreeController", ["$scope", "$http", "$modal", "updateDashboardService", function($scope, $http, $modal, updateDashboardService) {
$scope.selected_items = {};
updateDashboardService.update_dashboard();
var timer = setInterval(function() {
$scope.$apply(updateDashboardService.update_dashboard($scope, $http));
}, 1000 * 60);
What I am getting:
Error: [$injector:unpr] Unknown provider: $scopeProvider <- $scope <- updateDashboardService
Edit 2:
module.service('updateDashboardService', function($rootScope, $http){
this.update_dashboard = function() {
var url = Django.url('submission:active_list_ajax', {
site : site
});
$http.get(url).success(function(data) {
$rootScope.list = data.results;
});
};
});
As #Gopesh says create a factory method, or, you can do something like this in SubmissionTreeController:
$scope.$on("event:updateDashboard", function(){ update_dashboard() });
And in your other controller:
$http.post(url, $scope.selected_items).success(function(data) {
$scope.$emit("event:updateDashboard");
});

Categories