AngularJS: post data to server - javascript

I want to add data to my database using AngularJS. First I have to choose a category from a list of categories which I get from my server. After that a user can add a product to the database. I tried accomplishing this using:
AngularJS
categories = angular.module('categories', []);
categories.controller("category",function($scope, $http){
var serviceBase = 'api/';
$http.get(serviceBase + 'categories').then(function (results) {
$scope.categories = results.data;
for(var i = 0; i < $scope.categories.length; i++){
var categories = $scope.categories[i];
}
$scope.product = function($scope, $http, $catID){
$http.post(serviceBase + 'productadd/3/1/Icetealemon/5').then(function(results){
});
}
});
});
HTML
<table id="app2" ng-app="categories" ng-cloak="" class="table table-hover">
<tr >
<th colspan="5">Add product</th>
</tr>
<tr ng-form name="addproductForm" novalidate ng-controller="category">
<td colspan="1">
<select class="form-control m-b-10">
<option ng-repeat= "c in categories">{{c.categoryName}}</option>
</select>
</td>
<td colspan="1">
<select class="form-control m-b-10">
<option>Antwerpen</option>
<option>Leuven</option>
</select>
</td>
<td colspan="1">
<input type="text" class="form-control" placeholder="Name" ng-model="catID"></input>
</td>
<td colspan="1">
<input type="text" class="form-control" placeholder="Price" width="10%"></input>
</td>
<td colspan="1">
<input type="submit" class="btn btn-success" ng-click="product()"></input>
</td>
</tr>
</table>
I am not even using the ng-models to use the data of my html. It's still hard coded because it doesn't even work then. I am getting en error:
TypeError: Cannot read property 'post' of undefined
What am i doing wrong with my $http.post?

categories = angular.module('categories', []);
categories.controller("category",function($scope, $http){
var serviceBase = 'api/';
$http.get(serviceBase + 'categories').then(function (results) {
$scope.categories = results.data;
for(var i = 0; i < $scope.categories.length; i++){
var categories = $scope.categories[i];
}
$scope.product = function($scope, $http, $catID){
// NOTE: This '$http' is $scope.product function parameter
// variable `$http` not angular '$http'
$http.post(serviceBase + 'productadd/3/1/Icetealemon/5').then(function(results){
});
}
});
});
Remove $http parameter from $scope.product function.
Also, look at https://docs.angularjs.org/tutorial/step_05 about angular dependency issue during minification and how to solve it.

Related

Angular.js - Redirection is cleaning my $scope(?)

I have an $ngController that is being used in two views. The first view has an <table> with ng-repeat that lists all my data from the db.
I get the selected object form the table by using get($index) and set it to a $scope variable.
The problem is that when i cannot use this same $scope variable on the other view, because its value is undefined. Both views share the same ng-controller.
My Question is: is the redirection cleaning my $scope? Is there any way i can share this data between pages since my application isn't single page?
Things i tried:
1 - Share data through a factory
2 - Using $rootScope
First View - Table with ng-repeat
<table class="table table-striped">
<thead>
<tr>
<th>CNPJ</th>
<th>Razão Social</th>
<th>Ações</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="company in companies | filter:{companyName:searchString}">
<td> {{ company.cnpj }}</td>
<td> {{ company.companyName }}</td>
<td>
Visualizar
<button type="button" class="btn btn-warning btn-xs">Editar</button>
<button type="button" class="btn btn-danger btn-xs">Deletar</button>
</td>
</tr>
</tbody>
</table>
Controller
angular.module("distCad").controller("adminCtlr", function($scope, $http, config, $window, $cacheFactory){
$scope.searchTerm = null;
$scope.hideSearcAlert = true;
$scope.companies = [];
$scope.cache = $cacheFactory('companyCache');
$scope.expireLogin = function(){
localStorage.removeItem("type");
$window.location.href = "/";
}
$scope.getResults = function(){
$scope.searchTerm = true;
$http.get("/api/companies").then(
function successCallback(response){
$scope.companies = response.data;
},
function errorCallback(response){
console.log("aaaa" + response);
}
);
}
$scope.getCompany = function(){
return $scope.cache.get("company");
}
$scope.setCompanyFromTable = function(index){
$scope.cache.put("company", $scope.companies[index]);
}
});
Destination View - Part where i am testing
<div class="container" ng-init="getCompany()">
<div class="row">
<div class="col-md-12">
<h2>Dados da empresa {{cache.get("company").companyName}}</h2>

Get data from row when clicked and display to editable dialog box

I'm trying to use Angularjs to get data from a row in a table when it is clicked and display it in an editable dialog box. How can I do this? Here's what I have so far:
<table>
<thead>
<tr>
<th>ID No.</th>
<th>Firstname</th>
<th>Lastname</th>
<th>Gender</th>
<th>Time</th>
<th>Date</th>
<th>Type</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="walkin_member in data | filter:searchFilter">
<td><a class="click">{{walkin_member.id}}</a></td>
<td>{{walkin_member.firstname}}</td>
<td>{{walkin_member.lastname}}</td>
<td>{{walkin_member.gender}}</td>
<td>{{walkin_member.time}}</td>
<td>{{walkin_member.datestamp}}</td>
<td>{{walkin_member.type}}</td>
</tr>
</tbody>
</table>
This is my dialog box markup:
<div id="dlgbox">
<div id="dlg-header">Information</div>
<div id="dlg-body">
Firstname <input type="text" value="{{walkin_member.firstname}}"><br/>
Lastname <input type="text" value="{{walkin_member.lastname}}"><br/>
Gender <input type="text" value="{{walkin_member.gender}}"><br/>
Type <input type="text" value="{{walkin_member.type}}"><br/>
</div>
<div id="dlg-footer">
<button onclick="dlgUpdate()">Update</button>
<button onclick="dlgExit()">Exit</button>
</div>
</div>
Here's my controller:
myApp.controller('loglistController', ['$scope', '$http', function ($scope, $http) {
$http.get("../php/loglistajax.php")
.success(function(data){
$scope.data = data;
})
.error(function() {
$scope.data = "error in fetching data";
});
}]);
the dialog box is hidden, it will just show if the function is triggerd onclick
here's my javascript.
function showDialog(){
var whitebg = document.getElementById("white-background");
var dlg = document.getElementById("dlgbox");
whitebg.style.display = "block";
dlg.style.display = "block";
var winWidth = window.innerWidth;
dlg.style.left = (winWidth/2) - 480/2 + "px";
dlg.style.top = "150px";
}
Add an ng-click event to the anchor tag in each row and pass the current member to the method.
<tr ng-repeat="walkin_member in data | filter:searchFilter">
<td>
<a class="click" href="#"
ng-click="showInEdit(walkin_member)">{{walkin_member.id}}</a>
</td>
</tr>
Now in your controller, Add a new property to hold the selected member and a method called showInEdit()
myApp.controller('loglistController', ['$scope', '$http', function ($scope, $http) {
$scope.data=[];
$scope.selectedMember={ firstname:"",lastname:"",gender:"",type:"" }; //new property
$http.get("../php/loglistajax.php")
.success(function(data){
$scope.data = data;
})
.error(function() {
$scope.data = "error in fetching data";
});
$scope.showInEdit=function(member){
$scope.selectedMember = member;
};
}]);
And in your model dialog, you will use the selectedMember property.
<div id="dlgbox">
<div id="dlg-header">Information</div>
<div id="dlg-body">
Firstname <input type="text" ng-model="selectedMember.firstname" />
</div>
</div>

Define and get values from angularJS table

Here is my angularjs code to get values in a table and save. If I put some data in table and save, Its working fine but if I click save without entering any data in table it shows error as
TypeError: $scope.item is undefined
Here is my code and please help me. I am a newbie in angularJS
<div ng-app="Myapp">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular-route.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular-messages.js"></script>
<script>
var Myapp = angular.module('Myapp', ["ngRoute"]);
</script>
<div ng-controller="orderFormController">
<table id="item_table">
<thead>
<tr class="headings">
<th class="column-title">Item </th>
<th class="column-title">Rate</th>
</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input type="text" name="item" ng-model='item[0]'>
</td>
<td>
<input type="text" name="rate" ng-model='rate[0]'>
</td>
</tr>
<tr>
<td>
<input type="text" name="item" ng-model='item[1]'>
</td>
<td>
<input type="text" name="rate" ng-model='rate[1]'>
</td>
</tr>
</tbody>
</table>
<button type="button" ng-click='saveorder()' >SAVE ORDER</button>
</div>
<script>
Myapp.controller('orderFormController', ['$scope', '$http', function ($scope, $http) {
var data = {};
data['item'] = [];
$scope.saveorder = function () {
var rowCount = 3;
for (i = 1; i < rowCount; i++) {
data['item'][i] = {'item': $scope.item[i], 'rate': $scope.rate[i]}
}
alert(data);
}
}]);
</script>
$scope.item is not defined anywhere except for in that for loop, if there are no values in the table, then $scope.item will remain undefined. You could simply declare it prior to the for loop, and set some init values, which could be done in the controller, or by using the ng-init directive.
Also, I would recommend using the ng-repeat directive for your table rows, it will create a template per item from a collection, which makes your code easier to manage. Here's the documentation: ngRepeat
modify your html to only include this not 2 rows of input
<td>
<input type="text" name="item" ng-model='item'>
</td>
<td>
<input type="text" name="rate" ng-model='rate'>
</td>
and modify your saveOrder
$scope.saveorder = function () {
if (!($scope.item.length && $scope.rate.length)){
alert('can\'t be empty');
return;
}
data['item'].push({'item': $scope.item, 'rate': $scope.rate});
$scope.item = "";
$scope.rate = "";
console.log(data['item'][data['item'].length - 1]);
alert(data);
}

AngularJS: table edit data + update server

I have managed to create a table using AngularJS. In this table I show products from my datbase which can be filtered on category or some other keywords. Now the user should be able to alter this data in this table to update the data in the database.
AngularJS
categorieFilter = angular.module("categorieFilter", [])
categorieFilter.controller("catFilter", ["$scope", "store", function($scope, store){
$scope.search = "";
$scope.products = [];
$scope.categories = [];
store.getCategories().then(function(data){
$scope.categories = data;
})
store.getProducts().then(function(data){
$scope.products = data;
})
$scope.filterProductsByCats = function(category){
$scope.search = category;
};
}])
categorieFilter.factory('store', function($http, $q){
function _getCategory (){
var deferred = $q.defer();
$http.get('api/categories').success(function (data) {
deferred.resolve(data);
})
return deferred.promise;
}
function _getProducts (){
var deferred = $q.defer();
var prods = [];
$http.get('api/products').success(function (data) {
for(var i = 0;i<data.length;i++)
{
prods[i] = {name: data[i][0], category: data[i][2], price: data[i][1]};
}
deferred.resolve(prods);
})
return deferred.promise;
}
return {
getCategories: _getCategory,
getProducts : _getProducts
};
});
HTML table
<div ng-app="categorieFilter" ng-cloak="" ng-controller="catFilter">
<div class="input-group">
<input type="text" name="table_search" class="form-control input-sm pull-right" ng-model="search" placeholder="Search"/>
<div class="input-group-btn">
<button class="btn btn-sm btn-default">
<i class="fa fa-search"></i>
</button>
</div>
</div>
<div>
<input type="submit" class="btn btn-success" style="margin:10px; width:30%;" ng-repeat="cat in categories" ng-click="filterProductsByCats(cat.categoryName)" value="{{cat.categoryName}}">
</div>
<table class="table table-hover">
<tr style="background-color:#ddd;">
<th colspan="4" style="text-align:left; font-size:16px;"> Category </th>
<th colspan="4" style="text-align:left; font-size:16px;"> Product </th>
<th colspan="4" style="text-align:left; font-size:16px;"> Price </th>
</tr>
<tr ng-repeat="product in products | filter:search | orderBy: 'category'">
<td colspan="4">{{product.category}}</td>
<td colspan="4">{{product.name}}</td>
<td colspan="4">{{product.price}}</td>
</tr>
</table>
Any ideas or reccomendations to get this done?
A library I like to use to achieve the editing of data, is angular xeditable. http://vitalets.github.io/angular-xeditable/
Then save it by posting it back to the webapi

Call method from another ng-app in angular js

I have 2 ng-app block on same page. One for listing items, and the other one is for insert. I want to call listing function after I have finished insert.
I have tried something but I couldn't succeeded in.
I found some documents about calling functions on same ng-app but i need to call a function from another ng-app.
Here is my code, please help.
<body>
<div id="UserControllerDiv" ng-app="UserTableApp" ng-controller="UsersController" class="form-group">
<br /><br />
<p>Search : <input type="text" ng-model="search" /></p>
<table class="table table-hover">
<thead>
<tr>
<th>First Name</th>
<th>Middle Name</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="u in users | filter:search">
<td>{{ u.FirstName }} </td>
<td>{{ u.MiddleName }} </td>
</tr>
</tbody>
</table>
</div>
<br />
<div id="UserFormDiv" ng-app="UserFormApp" ng-controller="UserFormCtr" class="form-group">
<table class="form-group">
<tr>
<td>First Name</td>
<td> : </td>
<td><input type="text" ng-model="FirstName" class="" /> </td>
</tr>
<tr>
<td>Middle Name</td>
<td> : </td>
<td><input type="text" ng-model="MiddleName" /> </td>
</tr>
<tr>
<td></td>
<td></td>
<td>
<button ng-click="submit()">Save</button>
</td>
</tr>
</table>
</div>
<script>
var userTableApp = angular.module("UserTableApp", []);
userTableApp.controller("UsersController",
function UsersController($scope, $http) {
$http.get("http://localhost:10160/UserService/Users")
.success(function (response) { $scope.users = response; });
});
var userFormApp = angular.module("UserFormApp", []);
userFormApp.controller("UserFormCtr",
function UserFormCtr($scope, $http) {
$scope.submit = function () {
var dataObj = {
FirstName: $scope.FirstName,
MiddleName: $scope.MiddleName
};
var res = $http.post("http://localhost:10160/UserService/AddUser", dataObj);
res.success(function (data, status, headers, config) {
/****** Here I want to call the UsersController function of UserTableApp ************/
/* I tried the code below but it did not work */
var scope = angular.element(document.getElementById("UserControllerDiv")).scope();
scope.$apply(function () { scope.UsersController($scope, $http); });
/*************************************************************************************/
});
res.error(function (data, status, headers, config) {
alert("failure message: " + JSON.stringify({ data: data }));
});
}
});
angular.bootstrap(document.getElementById("UserFormDiv"), ['UserFormApp']);
</script>
Thank you for all your help...
Here is how you call function from other controller app.
var scope = angular.element(document.getElementById("UserControllerDiv")).scope();
scope.yourfunctionName();
And the flow will go to the Function mentioned.
For assurance you can check presence of your method in scope object in console.
You were just about right.

Categories

Resources