I have a "Remove All" button that removes all records from a Ng-table and MongoDB.
In my system, there are several views and each and every one of them display different data. Now, I don't know how to get the current page name and send it as a parameter for remove. It is working only if I insert to the code the name of the view and click on the button.
HTML:
<ul class="pager" ng-show="currentPage==login">
<li>
<button ng-click="removeLogs('$scope.logType')" id="deleteAllErrors" name="deleteError" class="btn btn-danger">Remove All</button></li>
</ul>
Angular:
// login, signUp, addErr, refreshLog, refreshErr, badProd - $scope.currentPage
$scope.removeLogs = function(logType){
console.log("Admin request to delete logType: "+logType+" & "+currentPage.current.name);
var rmLogs = {
'email': localStorageService.get('email'),
'password': localStorageService.get('password'),
'logType': logType
};
$http.post(''+appPath+'/removeLogs', rmLogs)
.then(function(data){
$scope.statusMsg = "Logs Deleted Successfully";
console.log("Admin X has delete logType");
$scope.updateAdmin();
});
};
You can inject $route in controller's DI and access the params like this.
var currentMethod = $route.current.params.name;
Or you can use $routeParams https://docs.angularjs.org/api/ngRoute/service/$routeParams
Related
Whenever I click on view the items are selected on same page. I need to display them on the new page, but I am not able to do that.
<html ng-app="countryApp">
<body ng-controller="CountryCtrl">
<div ng-repeat="x in models track by $index">
<button ng-click="select(x, $index)">View Me</button>
</div>
Selected Model:
<p> {{selected.name}} </p>
<p> {{selected.brand}} </p>
<p> {{selected.price}} </p>
<p> {{selected.quan}} </p>
<p> {{selected.sku}} </p>
</body>
Function:
<script>
var countryApp = angular.module('countryApp', []);
countryApp.controller('CountryCtrl', function ($scope){
$scope.select = function(brand) {
$scope.selected = brand;
}
$scope.models = [
{ brand: "Brand: Apple", id: 980190962, name: "Name: iPhone 5", price: "Price: $199", quan: "Quantity: 1", sku: "SKU:1234" },
{ brand: "Brand: Samsung", id: 298486374, name: "Name: Galaxy S3", price: "Price: $199", quan: "Quantity: 2", sku: "SKU:5678"}
]
});
</script>
</html>
You can use two options either store that selected user to localstorage or somewhere and read that in details view like
localStorage.setItem('myObj',JSON.stringify(brand));
and retrieve that in details view like
JSON.parse(localStorage.getItem('myObj'));
OR
I will prefare to use parent child relationship in this suppose you have a parent controller named 'CountryCtrl' and two child controllers 'CountryListCtrl' and 'CountryDetailCtrl'. List page is bind to 'CountryListCtrl' and details view is bind to 'CountryDetailCtrl' and on top you have 'CountryCtrl'. You can change your view using ng-include etc. When moving from List to Detail Controller set an object on parent controller and it will be accessible to both Controllers. You can learn about parent and child relationship in angularjs on internet there are tons of article available.
Thanks.
To show the details of the selected item in a new tab, there are multiple ways to achieve this. One way is to add a form with attribute target="_blank" (to open the action attribute in a new tab) and submit it in the select() function.
So you can add a form, like this:
<form id="openNewTabForm" target="_blank" method="GET"></form>
Then update the function to submit the form. There are multiple ways to pass the data about the selected phone - e.g. store the data in form fields, serialize the data and store it in a cookie, in localStorage, etc. Here is an example using hidden form fields:
$scope.select = function(phone) {
var form = document.getElementById('openNewTabForm');
form.action = action="selectedPhone.html";
Object.keys(phone).forEach(function(field,index) {
var input = form.elements[field]; //look for an existing form field for this field
if (input) { //update existing form field
input.value = phone[field];
}
else { //create a new form field for this
input = document.createElement('input');
input.type = 'hidden';
input.name = field;
input.value = phone[field];
form.appendChild(input);
}
});
form.submit();
$scope.selected = phone;
}
Then have a new page (e.g. selectedPhone.html) that takes the values submitted with the form. This could be a server-side page (e.g. with PHP, Ruby, etc), in which case you would set the attribute method="POST" on the form. Or you can just use a regular HTML page and process the query string. You could also use AngularJS + UI Router, VueJS, etc. to modify the URL after it has been loaded.
Take a look at this Plunker example I made for an example. I would have included a code snippet that would run here but SO doesn't (currently) allow having a form submission open a new tab because it is sand-boxed.
Another approach might be to use window.open() for opening a new browser window but that might lead to issues with popup blockers for some users.
You can open new modal on click of button function like following -
In controller:
$scope.showDetails = function(){
// open new html modal to show new screen using following
$ionicModal.fromTemplateUrl('templates/views/details.html',{
scope: $scope,
animation: 'none',
backdropClickToClose: false
}).then(function(modal){
$scope.modal= modal;
$scope.modal.show();
});
}
In HTML:
<div ng-repeat="x in models track by $index">
<button ng-click="showDetails (x, $index)">View Me</button>
</div>
By using new modal (screen) you can design as you required as well.
I am new to Angular and need your help on an issue with the ng-repeat of my app.
Issue:
I have an html page (event.html) and in the corresponding controller of the file, I make a request to a firebase collection and update an array ($scope.events). The issue is that the data from firebase takes a few seconds to load and by the time data arrives to $scope.events, ng-repeat has already been executed and it displays an empty screen. The items are displayed correctly the moment I hit on a button in the HTML page (event.html).
Sequence of events:
I have a login page (login.html) where I enter a user name and phone number and I click on the register button. I've configured this click on the register button to go to the new state (event.html).
Here is the controller code for login.html:
$scope.register = function (user) {
$scope.user = user.name;
$scope.phonenumber = user.phonenumber;
var myuser = users.child($scope.user);
myuser.set({
phone : $scope.phonenumber,
Eventid : " ",
name : $scope.user
})
var userid = myuser.key();
console.log('id is ' +userid);
$state.go('event');
}
The controller of event.html (the state: event) has the following code:
var ref = new Firebase("https://glowing-torch-9862.firebaseio.com/Users/Anson/Eventid/");
var eventref = new Firebase("https://glowing-torch-9862.firebaseio.com/Events");
var myevent = " ";
$scope.events = [];
$scope.displayEvent = function (Eventid) {
UserData.eventDescription(Eventid)
//UserData.getDesc()
$state.go('myevents');
//console.log(Eventid);
};
function listEvent(myevents) {
$scope.events.push(myevents);
console.log("pushed to array");
console.log($scope.events);
};
function updateEvents(myevents) {
EventService.getEvent(myevents);
//console.log("success");
};
ref.once('value', function (snapshot) {
snapshot.forEach(function (childSnapshot) {
$scope.id = childSnapshot.val();
angular.forEach($scope.id, function(key) {
eventref.orderByChild("Eventid").equalTo(key).on("child_added", function(snapshot) {
myevents = snapshot.val();
console.log(myevents) // testing 26 Feb
listEvent(myevents);
updateEvents(myevents);
});
});
});
});
$scope.createEvent = function () {
$state.go('list');
}
event.html contains the following code:
<ion-view view-title="Events">
<ion-nav-buttons side="primary">
<button class="button" ng-click="createEvent()">Create Event</button>
<button class="button" ng-click="showEvent()">Show Event</button>
</ion-nav-buttons>
<ion-content class="has-header padding">
<div class="list">
<ion-item align="center" >
<button class= "button button-block button-light" ng-repeat="event in events" ng-click="displayEvent(event.Eventid)"/>
{{event.Description}}
</ion-item>
</div>
</ion-content>
</ion-view>
The button showEvent is a dummy button that I added to the HTML file to test ng-repeat. I can see in the console that the data takes about 2 secs to download from firebase and if I click on the 'Show Events' button after the data is loaded, ng-repeat works as expected. It appears to me that when ng-repeat operates on the array $scope.events, the data is not retrieved from firebase and hence its empty and therefore, it does not have any data to render to the HTML file. ng-repeat works as expected when I click the dummy button ('Show Event') because a digest cycle is triggerred on that click. My apologies for this lengthy post and would be really thankful if any of you could give me a direction to overcome this issue. I've been hunting in the internet and in stackoverflow and came across a number of blogs&threads which gives me an idea of what the issue is but I am not able to make my code work.
Once you update your events array call $scope.$apply(); or execute the code that changes the events array as a callback of the $scope.$apply function
$scope.$apply(function(){
$scope.events.push(<enter_your_new_events_name>);
})
If you are working outside of controller scope, like in services, directive, or any external JS. You will need to trigger digest cycle after change in data.
You can trigger digest cycle by
$scope.$digest(); or using $scope.$apply();
I hope it will be help you.
thanks
In your case you have to delay the binding time. Use $timeout function or ng-options with debounce property in your view.
you have to set a rough time taken to get the data from the rest API call. By using any one of the methods below will resolve your issue.
Method 1:
var myapp = angular.module("myapp", []);
myapp.controller("DIController", function($scope, $timeout){
$scope.callAtTimeout = function() {
console.log("$scope.callAtTimeout - Timeout occurred");
}
$timeout( function(){ $scope.callAtTimeout(); }, 3000);
});
Method 2:
// in your view
<input type="text" name="userName"
ng-model="user.name"
ng-model-options="{ debounce: 1000 }" />
I have a posted json data form record and i want to edit that form onclick,
I am not able to populate my old data in the form to edit it.
<button style="margin:3px;" ng-click="put1(student)" onclick="opendiv();">Edit</button>
Here, student is an array and opendiv is to open model dialogue box.
self.put1 = function(student){
var studentname = student.name;
var studentid = student.id;
var studenttype = student.type;
var data = { studentname : self.newstudent.name,
studentid = self.newstudent.id ,
studenttype =self.newstudent.type
}
$http.put('/rest/student',data)
.success(function(data){
alert("updated"); })
.error(function(errResponse) {
console.error('Error while fetching notes');
});
};
What do you mean with old data when you say:
"I am not able to populate my old data"?!
If you are referring student's data as old data, be sure you have bind the students's data correctly to your input elements of your form, using ng-model directive, if you want to use AngularJS.
My advice is:
Use $scope, or $rootScope directive to save your student's data on the angular controller like "$scope.student".
Use ng-model directive to display your students list on the view like this
<form name="studentForm">
<input type="text" ng-model="student.name"/>
<button ng-click="edit();">Edit</button>
</form>
.
ng-model="student.name" will show you the old student's name, so you can edit it.
In angular controller implement your edit() function. like this
$scope.edit = function(){
var data = $scope.student; /*the student's name is automatically updated because of two-way data-binding*/
$http.put('/rest/student',data)
.success(function(data){
alert("updated"); })
.error(function(errResponse) {
console.error('Error while fetching notes');
});
}
I am fairly new to Angular an I am feeling lost in all of it's documentation.
Problem:
I am trying to create a button which has three phases:
Add User - Remove Request - Remove User
So if you want to add a user you click on the Add button, which
sends an ajax request to the server and if successful the button
should then turn into a Pending button.
In the pending state if you click on it again, your request will be
deleted and it will again turn back to a Add button.
The third phase is also if the user has accepted your request, you
will be seeing a Remove user button which when you click on
you will again see the Add button which if you click you will get
the Pending button and so forth.
So basically it is a familiar button if you've been using social networks.
When the page is loaded the user will see the users and the buttons for each user based on it's current condition (so the server will be handling this part). From this part Angular should handle the ajax calls and changing of the button per user connection request.
What I need:
I have done the Ajax part for sending the request. However I can't manage to handle the part which Angular needs to change the button to it's new state (for a specific user on the list, meaning the list has more than 1 user which you can send connection add/pending/delete requests.) I have tried different solutions but failed till now.
Some of my messy failure code which I have left unfinished:
Angular Controller:
foundationApp.controller('ConnectionButtonCtrl', function ($scope, $http) {
$scope.addUser = function(id) {
$http({
method : 'GET',
url : '/api/connections/add/'+id,
dataType: "html",
})
.success(function() {
$scope.activeId;
$scope.activeId = id;
$scope.isAdd = function(id){
return $scope.activeId === id;
};
})
};
$scope.removeRequest = function(id) {
$http({
method : 'GET',
url : '/api/connections/removeRequest/'+id,
dataType: "html",
})
.success(function() {
})
};
});
Laravel Blade View:
<span ng-controller="ConnectionButtonCtrl" >
<a class="label radius fi-plus" ng-show="!isRemove(1)" ng-click="addUser(1)"></a>
<a class="label radius fi-clock info" ng-show="isRemove(1)" ng-click="removeRequest(1)"></a>
<a class="label radius fi-x alert" ng-show="!isAdd(1)" ng-click="removeUser(1)"></a>
</span>
If I understand correctly, just use $index or user.id. I am assuming your buttons are on the same line as the user. If that's true then you are probably using an ng-repeat.
For example:
<div ng-repeat="user in users">
<a class="label radius fi-plus" ng-show="!isRemove(user.id)" ng-click="addUser(user.id)"></a>
<a class="label radius fi-clock info" ng-show="isRemove(user.id)" ng-click="removeRequest(user.id)"></a>
<a class="label radius fi-x alert" ng-show="!isAdd(user.id)" ng-click="removeUser(user.id)"></a>
<div> some user information {{user.name}} </div>
</div>
Then you can pass the id of the user with your ajax request. You can also use $index (as a parameter in my code instead for the index of the user in the array).
DEMO: http://plnkr.co/edit/hhOdNTV6ogJHhtXcM03a?p=preview
js
var app = angular.module('myApp', []);
app.controller('myController', function ($scope) {
$scope.users = {
user1: {
'status': 'add',
'statusClass': 'positive'
},
user2: {
'status': 'pending',
'statusClass': 'waiting'
},
user3: {
'status': 'remove',
'statusClass': 'negative'
}
};
$scope.handle = function (user) {
if (user.status === 'add') {
alert('send request to the user');
user.status = 'pending';
user.statusClass = 'waiting'
}
else if (user.status === 'pending') {
alert('send request to discard a connection req');
user.status = 'add';
user.statusClass = 'positive'
}
else {
alert('send req for removal');
user.status = 'add';
user.statusClass = 'positive'
}
};
});
app.$inject = ['$scope'];
HTML:
<body ng-app="myApp" ng-controller="myController">
<div ng-repeat="user in users">
User {{$index+1}} - <button ng-click="handle(user)" ng-class="user.statusClass">{{ user.status }}</button>
</div>
</body>
http://plnkr.co/edit/hhOdNTV6ogJHhtXcM03a?p=preview
I am very new about AngularJS things. Need to do file upload with other datas in form, I found some scripts and angular plugins but I am using my own service calls $xhr. I was able to send file but i got error, bug(not real error-bug, i just named like that) or i can not use AngularJS properly. Here it is:
.
JS
var app = angular.module('ngnNews', []);
app.factory('posts', [function () {...}]); // I reduced the codes
app.factory('$xhr', function () {
var $xhr = { reqit: function (components) { ... //My Xml HTTP Request codes here }}
return $xhr;
});
app.controller('MainCtrl', ['$http','$scope','$xhr','posts',
function ($http, $scope, $xhr, posts) {
$scope.posts = posts.posts;
$scope.files = [];
var newPost = { title: 'post one', upvotes: 20, downvotes: 5 };
$scope.posts.push(newPost);
$scope.addPost = function () {
$xhr.reqit({
form: document.getElementById('postForm'),
callbacks: {
success: function (result) {
if (result.success) {
console.log($scope.posts); //[FIRST OUT]
$scope.posts.push(result.post);
$scope.title = '';
console.log($scope.posts); //[SECOND OUT]
}
}
},
values: { upvotes: 0, downvotes: 0 },
files: $scope.files
});
...
}
}]);
.
HTML
<form action="/Home/FileUp" id="postForm" method="post" enctype="multipart/form-data">
<div class="form-group input-group">
<span class="input-group-addon">Post Title</span>
<input name="title" class="form-control" type="text" data-ng-model="title" />
</div>
<ul>
<li ng-repeat="file in files">{{file.name}}</li>
</ul>
<button class="btn btn-primary" type="button" data-ng-click="addPost()">Add New</button>
</form>
SCREEN
Sample post displayed in list
.
PROBLEMS
When I click first time Add New button everything works well until $scope.posts.push(result.post);. In console, [SECOND OUT] is here:
First object has $$hashKey but second object which sent from server(added by $scope.posts.push(result.post); function) doesn't have. I want to know why is this happening? But it's not only weird thing, when I second time click Add New button, everything completed successfully (No new logs in console, adding new post to list shown screen image above).
MAIN PROPLEM
I pushed returned value from the server but post list(in screen) is not affected when first click.
QUESTIONS
- What is happening? or
- What am I doing wrong? Thanks for any explanation.
You are doing nothing wrong with respect to $$hashkey if that is your concern. When you use ng-repeat with array of objects angular by default attaches a unique key to the items which is with the property $$hashkey. This property is then used as a key to associated DOM elements with the corresponding item in the array by identity. Moving the same object in array would move the DOM element in the same way in the DOM. You can avoid this (addition of additional property on the object by angular) by using track by with ng-repeat by providing a unique key on the object or a mere $index. So with that instead of creating a unique key and attaching it to $$haskey property angular will use the unique identifier you have provided to associate the DOM element with the respective array item.
ng-repeat="post in posts track by $index"
or (id you have a unique id for each of the object in the array, say id then)
ng-repeat="post in posts track by post.id"
And since you say you are using my xml http request code here, i am assuming it is not within the angular context so you would need to manually perform the digest cycle by using $scope.$apply() is on of those ways.
$scope.addPost = function () {
$xhr.reqit({
form: document.getElementById('postForm'),
callbacks: {
success: function (result) {
if (result.success) {
$scope.posts.push(result.post);
$scope.title = '';
$scope.$apply();//<-- here
}
}
},
But ideally you could wrap your xhr implementation with a $q and if you pass $q promise from your api, you wont need to perform a manual $scope.$apply() everywhere. Because $q promise chaining will take care of digest cycle invocation.