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');
});
}
Related
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
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 working on a small pet project that finds exchange rates and I am having trouble passing my input to the angular controller.
Say I have a datalist input that shows a selection of countries as you type:
<label for="ajax">From</label>
<input type="text" id="ajax" list="json-datalist">
<datalist id="json-datalist"></datalist>
And the items are populated using JavaScript:
// Get the <datalist> and <input> elements.
var dataList = document.getElementById('json-datalist');
var input = document.getElementById('ajax');
var fromCode = 'USD';
// Create a new XMLHttpRequest.
var request = new XMLHttpRequest();
// Handle state changes for the request.
request.onreadystatechange = function(response) {
if (request.readyState === 4) {
if (request.status === 200) {
// Parse the JSON
var jsonOptions = JSON.parse(request.responseText);
// Loop over the JSON array.
jsonOptions.forEach(function(item) {
// Create a new <option> element.
var option = document.createElement('option');
// Set the value using the item in the JSON array.
option.value = item.name;
fromCode = item.code;
// Add the <option> element to the <datalist>.
console.log(option);
dataList.appendChild(option);
});
// Update the placeholder text.
input.placeholder = "e.g. United States Dollar - USD";
} else {
// An error occured :(
input.placeholder = "Couldn't load currency options :(";
}
}
};
// Update the placeholder text.
input.placeholder = "Loading currencies...";
// Set up and make the request.
request.open('GET', 'js/currencies.json', true);
request.send();
The currencies.json file looks like this.
I am showing the user the country name and trying to pass the country code to the angular controller so it can find the right exchange rate for that country and display it.
Now my angular controller looks like this:
var myApp = angular.module("myApp", []);
myApp.controller("myController", ['$scope', '$http', function ($scope, $http) {
$scope.from = fromCode;
$http.get("https://api.fixer.io/latest?symbols=" + $scope.from)
.then(function (response) {
$scope.newRate = response.data;
});
$http.get("https://api.fixer.io/latest?base=USD")
.then(function (response) {
$scope.currencies = response.data;
});
}]);
The 'fromCode' is set to USD by default and is supposed to be updated as the datalist item changes which it does. I want angular to perform a new lookup every-time I change my datalist selection in my input form. How do I accomplish this?
You shouldn't be passing anything from your view to your controller. All of your data should be sourced from your controller. All of that javascript you have on your html page should be in your controller.
Once you've done that, you can bind your view to your controller using ng-repeat and ng-model and the data will get updated in your controller automatically.
I am trying to populate the ng-model from a value, but don't want it to update until it is saved. To do this I have the following code;
Controller;
var SettingsController = function (roleService) {
var ctrl = this;
ctrl.rename = function(name) {
ctrl.account.name = name;
};
roleService.role.settings().then(function (result) {
ctrl.account = result.data.account;
}, function (result) {
console.log(result);
});
};
A simple controller, it gets the current settings from a service and sets it to the ctrl.
When the rename(name) is called I update the name of the account (for now it just updates the scope but soon it will update also the back-end)
To rename your account I have the following piece of code
<input type="text" data-ng-model="account.name" />
<button type="button" data-ng-click="ctrl.rename(account.name)">
Rename
</button>
I use controler as so ctrl == SettingsController
Now I use data-ng-model="account.name" to update the name. This is done so I only update the name when the button is called. The only issue is how do I get the ctrl.account.name value to the input, without bubbling it up.
I could add $scope to my controller with $scope.account but that seems overkill to me. Isn't there a way to copy/populate a ng-model from an other value or some kind?
To get to the controller I use the angular routerProvider;
$routeProvider
.when('/settings/', {
templateUrl: '/user/template/settings/',
controller: 'SettingsController',
controllerAs: 'ctrl'
});