i have a textbox called item and when the page loads i want to get a value from the localstorage and put it in the textbox item which i later send to the database.
HTML:
<div ng-controller="newitem_ctrl">
<input name="item" type="text" id="item" placeholder="Name of Item" ng-model="item" required="required">
</div>
JS:
.controller('newitem_ctrl', function($scope,$http,$location,$ionicLoading,$ionicPopup, $timeout){
$scope.item = localStorage.getItem("shop_id")
$scope.insertnew = function() {
$ionicLoading.show({template: '<p>Adding...</p><ion-spinner></ion-spinner>'});
event.preventDefault();
$http.post("http://localhost/myweb/insert.php",
{'item':$scope.item,'quantity'})
.success(function(data,status,headers,config){
console.log(data)
{$ionicLoading.hide();}
}).error(function(error){
console.error(error);
});
}
})
Related
I have my code in angularjs and nodes js.
I have created a form in which there is two drop-down lists, the second drop-down list is dependent on the first dropdown list selected value, so the dropped down list selected value should be pass in the URL and in the backend options related to that selected id should be fetched for the second drop-down list.
My codes are:
Html Code: In this code second select tag is empty
<div class="form-group" ng-controller="viewCompanyCtrl">
<label class="col-sm-2 control-label">Company: </label>
<div class="col-sm-10">
<select class="form-control m-b" ng-valid ng-not-empty
ng-model="recom.compName",id ="company" name="account"
ng-options = "x as x.compName for x in companyInfo">
</select>
</div>
</div>
<div class="form-group">
<label style="position: relative; left:15px; top: 30px">Demographics:</label>
<div style = "position: relative; left:196px">
<select multiple chosen class="chosen-select" ng-valid ng-not-empty
ng-model="recom.demo",id ="demo" name="account8" tabindex="4"
style = "width:890px;" >
</select>
</div>
</div>
controller.js (through this function the values are shown in first list)
function viewCompanyCtrl($scope,$http,$state)
{
$http.get('/viewCompany')
.success(function(data){
$scope.companyInfo = data;
console.log($scope.companyInfo);
})
.error(function(){
console.log("error");
})
config.js(this is the state of the page)
.state('Admin.AddRecommendation',{
url: "/AddRecommendation/:compId",
templateUrl: "views/AddRecommendation.html",
params: {compId:null},
})
Please help how to pass the id and get it in the backend.
Thanks
The .success method had been removed from the AngularJS framework.
To pass a URL parameter in an HTTP get request, use the params property:
var params = { compname: $scope.recom.compName };
var config = { params };
$http.get(url, config)
.then(function(response) {
var data = response.data;
console.log(data);
}).catch(function(response) {
console.log("ERROR: ", response);
});
For more information, see
AngularJS $http Service API Reference
im not sure the title explains clear enough what im trying to do, so im gonna try to explain here. i did the blog app from the book angularjs - from novice to ninja. because the api that the book uses is not working anymore, there were some functionalities i wasn't able to test. so later i did another tutorial of phalcon and build and api to do what the one in the angularjs book was supposed to. the api works fine (tested with postman, and also i use it for the login, so the blog app reaches it but i was only able to make it work in the login so far). so i have some doubts about the data i get from the api and how to show it in the for when i try to update one of the posts.
so the services.js file is like this:
angular.module('spBlogger.admin.services', []).
factory('Post', ['$resource', 'API_ENDPOINT', function ($resource, API_ENDPOINT) {
return $resource(API_ENDPOINT, {id:'#_id'}, {
update: {
method: 'PUT'
}
});
}]).
service('popupService', ['$window', function($window){
this.showPopup = function(message){
return $window.confirm(message); //Ask the users if they really want to delete the post entry
}
}]).
value('API_ENDPOINT', 'http://testing-phalcon/api/posts/:id');
the controller.js file:
controller('PostUpdateController', ['$scope', 'Post', '$stateParams', function ($scope, Post, $stateParams) {
console.log('in PostUpdateController');
$scope.post = Post.get({id:$stateParams.id}); //Obtain the Post from backend. Search by Id
console.log($scope.post);
$scope.buttonText = "Update"; // Set initial label for button
$scope.updatePost = function(){
$scope.buttonText = "Updating. . ."; //Once clicked change button text
$scope.post.$update(function(){
$state.go('admin.postViewAll'); //Once updated go to state 'admin.postViewAll'
});
}
}])
the admin-update-post.html file that loads the form:
<div class="row">
<div class="col-xs-8">
<form name="postForm" ng-submit="updatePost()" class="form-horizontal" novalidate role="form">
<div ng-include="'modules/admin/views/_form.html'"></div>
</form>
</div>
</div>
and finally the _form.html:
<div class="form-group" ng-class="{'has-error':postForm.title.$dirty && postForm.title.$invlaid}">
<label for="title" class="col-sm-2 control-label">Post Title</label>
<div class="col-sm-10">
<input type="text" name="title" ng-model="post.title" ng-required="true" class="form-control" id="title" placeholder="Title">
<span>Permalink:<i>/posts/[id]/{{post.title | permalink}}</i></span>
<span class="error-message" ng-show="postForm.title.$dirty && postForm.title.$invalid">Title is mandatory</span>
</div>
</div>
<div class="form-group" ng-class="{'has-error':postForm.content.$dirty && postForm.content.$invalid}">
<label for="content" class="col-sm-2 control-label">Content</label>
<div class="col-sm-10">
<textarea cols="8" rows="6" name="content" class="form-control" ng-model="post.content" ng-required="true" id="content" placeholder="Content"></textarea>
<span>{{post.content | wordcount}} words</span><br/>
<span class="error-message" ng-show="postForm.content.$dirty && postForm.content.$invalid">You need to have some content!</span>
</div>
</div>
<div class="form-group" ng-class="{'has-error':postForm.keywords.$dirty && postForm.keywords.$invalid}">
<label for="keywords" class="col-sm-2 control-label">Keywords</label>
<div class="col-sm-10">
<input type="text" name="keywords" class="form-control" id="keywords" ng-pattern="/^[\w,]+$/" ng-model="post.keywords" placeholder="Comma separated keywords" />
<span class="error-message" ng-show="postForm.keywords.$dirty && postForm.keywords.$invalid">Sorry! No special characters allowed here</span>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-success" ng-disabled="postForm.$invalid">{{buttonText}}</button>
</div>
</div>
What i want to achieve is that when i select a post that i want to update, i want to display the form with the data from the post in the title input, the content in the textarea, and the keywords in the keywords input.
what i tried in the controller (forgive me if it looks bad, but im very new to angular) is:
$scope.thepost = {};
$scope.thepost.title = $scope.post.title;
but this obvioulsy doesn't work. i know the data is getting to the controller because of the console logs (i can see the api answers correctly), but im not sure first how to parse it and then how to pass it from the controller to the view. any help is welcome. thanks!
EDIT
the template that displays all the posts available is admin-all-posts.html:
<div class="row">
<div class="col-xs-8">
<table class="table">
<tr>
<td><h3>View All Posts</h3></td>
<td></td>
</tr>
<tr ng-repeat="post in posts | orderBy:'-_id'">
<td>{{post.title}}</td>
<td>
<a class="btn btn-primary" ui-sref="admin.postUpdate({id:post.id})">Edit</a>
<a class="btn btn-danger" ng-click="deletePost(post)">Delete</a>
</td>
</tr>
</table>
</div>
</div>
the controller that loads the posts from the api is in controllers.js:
controller('PostListController', ['$scope', 'Post', 'popupService', '$state', function ($scope, Post, popupService, $state) {
$scope.posts = Post.query(); //Obtain all the posts from backend
$scope.deletePost = function(post){
if(popupService.showPopup('Really delete this?')){ //Ask for confirmation
post.$delete(function(){
$state.go('admin.postViewAll', undefined, { //once deleted reload the state
reload: true
});
});
}
}
}])
i hope this helps
Examine the $scope.post after the data arrives from the server:
controller('PostUpdateController', ['$scope', 'Post', '$stateParams', function ($scope, Post, $stateParams) {
console.log('in PostUpdateController');
$scope.post = Post.get({id:$stateParams.id}); //Obtain the Post from backend. Search by Id
̶c̶o̶n̶s̶o̶l̶e̶.̶l̶o̶g̶(̶$̶s̶c̶o̶p̶e̶.̶p̶o̶s̶t̶)̶;̶
$scope.post.$promise.then(function() {
console.log($scope.post);
}).catch(function(error) {
console.log("ERROR:", error);
});
$scope.buttonText = "Update"; // Set initial label for button
$scope.updatePost = function(){
$scope.buttonText = "Updating. . ."; //Once clicked change button text
$scope.post.$update(function(){
$state.go('admin.postViewAll'); //Once updated go to state 'admin.postViewAll'
});
}
}])
It is important to realize that invoking a $resource object method immediately returns an empty reference (object or array depending on isArray). Once the data is returned from the server the existing reference is populated with the actual data.
I am a newbie to AngularJS. I have an input text box in my html code which is used to select a city, which is coming from the data base. For that I am calling the API. The results are populating the datalist, which is working fine. But as I select a item from the datalist, it is calling the method once again and it is showing the same result which I had selected. I know it is because of ng-change. can anyone give me a solution to this problem or any idea that would help me. Thanks for your help in advance
My HTML :
<input type="text" list="cityList" class="form-control" placeholder="Select City" ng-model="selectcity" ng-change="searcity()" class="form-control" id="seacityincoucat">
<datalist id="cityList">
<option ng-repeat="city in cities.results" value="{{city.name}}">
</datalist>
Controller :
$scope.searcity = function () {
var ciseurl = urlcs + $scope.selectcity;
$http.get(ciseurl, config).then(function (response) {
if (response.data.status === '$200') {
$scope.cities = response.data;
var x = $scope.cities.results;
couponSvc.setCityId(x[length].id);
}else{
alert("try some thing else");
}
});
};
Use ng-blur instead of ng-change
<input type="text" list="cityList" class="form-control" placeholder="Select City" ng-model="selectcity" ng-blur="searcity()" class="form-control" id="seacityincoucat">
Use ngKeyPress
<input type="text" list="cityList" class="form-control" placeholder="Select City" ng-model="selectcity" ng-keypress="searcity()" class="form-control" id="seacityincoucat">
I'm trying to show some editable results to the users, so I show them through an input field. This is a basic example of what I'm doing:
<div class="form-group">
<label>First number</label>
<input type="text" ng-model="first" ng-required="true" class="form-control">
</div>
<div class="form-group">
<label>Second number</label>
<input type="text" ng-model="second" ng-required="true" class="form-control">
</div>
<div class="form-group">
<label>The sum is: {{first + second }}</label>
<input type="text" ng-model="result" ng-required="true" class="form-control">
</div>
In the result's div, I used a label to test if the result is being obtained correctly, and it is. But if I edit the first or second values, the input's result doesn't update.
This is the controller used (yeah, the form is in a modal):
var ModalInstanceCtrl = function ($scope, $modalInstance) {
$scope.result = $scope.first + $scope.second;
$scope.confirm = function () {
$modalInstance.close(result);
};
$scope.cancelNewBet = function () {
$modalInstance.dismiss('cancel');
};
};
I thought the value was supposed to get automatically updated once I define how it is obtained. But clearly it misses something to change the result through script...
Thanks in advance.
What do you want to happen when the user edits the results input? Do you want the data binding to break (I assume not and ignore this possibility)? Do you want one of the inputs to adjust to the proper value?
If you only want to display the output, do this, in your controller:
$scope.result = function() { return $scope.first + $scope.second; }
And in your view:
{{ result() }}
But if you want the user to be able to edit the result and (let's say) have second be assigned (result - first), then you'd want something like this in your view (by the way, note the type="number"):
<input type="number" ng-change="adjustResult()" ng-model="first">
<input type="number" ng-change="adjustResult()" ng-model="second">
<input type="number" ng-change="adjustInput()" ng-model="result">
And in your controller:
$scope.adjustResult = function() {
$scope.result = $scope.first + $scope.second;
};
$scope.adjustResult(); // initialize result
$scope.adjustInput = function() {
$scope.second = $scope.result - $scope.first;
}
I have a form with checkboxes and other input fields.
The data-ns-form directive is used for submitting form data via ajax. The controller for this form is UserController.
HTML
<div ng-controller="UserController">
<form data-ns-form="formData">
Full Name : <input type="text" name="fullname" ng-model="formData.fullname" />
Favourite Beverage :
<label>
<input type="checkbox" name="beverages[]" ng-model="formData.beverages[0]" value="coffee"> Coffee
</label>
<label>
<input type="checkbox" name="beverages[]" ng-model="formData.beverages[1]" value="tea"> Tea
</label>
<label>
<input type="checkbox" name="beverages[]" ng-model="formData.beverages[2]" value="colddrinks"> Cold Drinks
</label>
<button type="submit"> Send </button>
</form>
</div>
Controller
app.controller('UserController', function($scope){
$scope.formData = {fullname : '', beverages : []};
});
Directive
app.directive('nsForm', function(){
return {
restrict : "A",
scope: {
formData : "=nsForm"
},
link : function(scope, iElem, iAttr) {
$(iElem).on('submit', function(e) {
e.preventDefault();
console.log("FORM DATA");
console.log(scope.formData);
});
}
}
});
A little description
When I submit the form I get boolean TRUE for checked checkboxes, but instead I want the value inside the value attirbute. For instance, If I checked 'coffee' and 'Cold Drinks', I get beverages=[true,false,true], but what do I want is beverages['coffee','colddrink'].
What is the AngularJS way of doing it?
And Also.
Is there any preferred way of submitting form in AngularJS instead of creating directives myself ?
I don't see any reason for the "name" attribute here. You need to use ng-click with a function to save your data - and that should be taken care of by a service. There's a lot you can do with angular...search the docs for anything you're doing (see checkboxes in the docs, for example).
Live demo here (click).
<div ng-controller="UserController">
Favourite Beverage :
<label>
<input type="checkbox" ng-model="formData.beverages[0]" ng-true-value="coffee">Coffee
</label>
<label>
<input type="checkbox" ng-model="formData.beverages[1]" ng-true-value="tea">Tea
</label>
<label>
<input type="checkbox" ng-model="formData.beverages[2]" ng-true-value="colddrinks">Cold Drinks
</label>
<button ng-click="save()"> Send </button>
</div>
js:
var app = angular.module('myApp', []);
app.factory('myService', function($http) {
var myService = {
save: function(data) {
//your ajax call here
console.log(data);
}
};
return myService;
});
app.controller('UserController', function($scope, myService) {
$scope.formData = {};
$scope.formData.beverages = [];
$scope.save = function() {
myService.save($scope.formData);
};
});
Also, you should probably have all of your data (the drink values, for example) in your javascript rather than the html, then bind it to the page. Or in the database, then into js, then onto the page. That all depends on how dynamic your information needs to be - just be sure to think ahead.