get value from json to angularjs object - javascript

I want to get value from this JSON response into angular js object.
[{"label":"Test","value":""," Test2":"","required":"mandatory","type":"text","typeemail":""}]
into angularjs object, here is .html
<tr ng-repeat="item in searched = (coba | filter:customerid | filter:search ) | coba:(currentPage-1)*itemsPerPage |limitTo:viewby ">
<td>
<p>{{item.additionaldata_pay}}</p>
</td>
</tr>
here is .js file
app.controller("cobacont", ['$scope','$http',function($scope,$http) {
$scope.cari = function () {
$http.get('...a='+$scope.month).then(function(response){
$scope.coba = response.data;
});
}
}]);

var app = angular.module('main-App', []);
app.controller('customersCtrl', function($scope,$http) {
$scope.records = [];
$http.get("https://...a='+$scope.month")
.then(function (response) {
console.log(response.data);
$scope.records = response.data;
});
});
here is my html table
<tr dir-paginate="value in data | itemsPerPage:5" total-items="totalItems" ng-repeat="user in records">
<td>{{$index+1}}</td>
<td >{{user.label}}</td>
<td >{{user.value}}</td>
<td>{{user.required}}</td>
<td>
<button data-toggle="modal" data-target="#edit-data" class="btn btn-primary" ng-click="selectedUser(user)">Edit</button>
<button ng-click="DeleteUser(user)" class="btn btn-danger" data-toggle="modal" data-target="#delete-data">Delete</button>
</td>
</tr>

It's best that you put all data processing in your controller. And leaving the HTML to display your data only.
So, in your controller, add another method that will do your search, filter, and pagination, and the result can then be used in your view.
$scope.getData = function () {
var data = $filter('filter')($scope.coba, $scope.searchQuery);
// do pagination here...
return data;
}
Your HTML can then become something like this:
<tr ng-repeat="item in getData()">
<td>
<p ng-bind="item.additionaldata_pay"></p>
</td>
</tr>

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>

Having a formular call a controller in AngularJS

I'm having a little issue with learning AngularJS. I'm not 100% sure what are controller about. For exemple, i have the following html div which simply display the result of a SQL request :
<div ng-app="searchApp" ng-controller="searchCtrl">
<table>
<tr ng-repeat="x in names">
<td>{{ x }}</td>
</tr>
</table>
</div>
And here's the controller :
<script>
var app = angular.module('searchApp', []);
app.controller('searchCtrl', function($scope, $http)
{
$http.get("server.php")
.then(function (response)
{
$scope.result = response.data;
})
.then(function(response){
console.log(response);
})
});
</script>
server.php is returning a simple array of strings, so the page display immediatly a list of names. I would like to add a button on this page, and display this list only AFTER the button has been clicked. I tried to add a form :
<div ng-app="searchApp" ng-controller="searchCtrl">
<form class="well form-search">
<button type="submit" class="btn" ng-click="search()">Search</button>
</form>
<table>
<tr ng-repeat="x in result">
<td>{{ x }}</td>
</tr>
</table>
</div>
but this form is calling the search() function, which doesn't exist right now. I would like to call the controller instead.
I don't know if i have made myself very clear, sorry.
//template (no form tag needed)
<button type="button" class="btn" ng-click="search()">Search</button>
//controller
$scope.search = function(){
$http.get("server.php")
.then(function (response)
{
$scope.result = response.data;
})
.then(function(response){
console.log(response);
})
}

Getting Error: [ngRepeat:dupes] in ng-repeat using angular.js

I am getting the following error while i have no data using ng-repeat in Angular.js
Error:
Error: [ngRepeat:dupes] http://errors.angularjs.org/1.4.6/ngRepeat/dupes?p0=user%20in%20objHodUserData&p1=string%3Al&p2=l
at Error (native)
at http://oditek.in/Gofasto/js/angularjs.js:6:416
at http://oditek.in/Gofasto/js/angularjs.js:279:39
at Object.fn (http://oditek.in/Gofasto/js/angularjs.js:129:128)
at n.$digest (http://oditek.in/Gofasto/js/angularjs.js:130:206)
at n.$apply (http://oditek.in/Gofasto/js/angularjs.js:133:236)
at g (http://oditek.in/Gofasto/js/angularjs.js:87:376)
at K (http://oditek.in/Gofasto/js/angularjs.js:91:448)
at XMLHttpRequest.z.onload (http://oditek.in/Gofasto/js/angularjs.js:92:462)
I am explaining my code below.
<tbody id="detailsstockid">
<tr ng-repeat="user in objHodUserData ">
<td>{{$index+1}}</td>
<td>{{user.user_name}}</td>
<td>{{user.email}}</td>
<td>{{user.mob_no}}</td>
<td>{{user.login_name}}</td>
<td ng-if="user.user_status==1">Enable</td>
<td ng-if="user.user_status==0">Disable</td>
<td>
<a ui-sref='hod.user'>
<input type='button' class='btn btn-xs btn-green' value='Edit' ng-click="editUserData(user.user_id)" >
</a>
</td>
<td>
<a ui-sref='hod.user'>
<input type='button' class='btn btn-xs btn-red' value='Delete' ng-click="deleteUserData(user.user_id);" >
</a>
</td>
</tr>
</tbody>
When the object objHodUserData has no data these type error is coming.I tried to resolve this by using track by $index. By using this error has gone but 4 blank rows are generating.Here i need when there is no data present no rows will generate without any error and when data will be there it will display.Please help me to resolve this error.
I had the same problem, and I solved it by wrapping all the <tbody> within a <div> element.
and inserting ng-show in this div element like that
<div ng-show="hasElements()">
and in your controller you have a $scope function to check if there is elements in the object like that:
$scope.hasElements = function(){
return objHodUserData.length ===0;
}
and that should work.
let me if it solved your problem.
Cheers.
Try using ng-if along with ng-repeat.It should be ng-if="objHodUserData.length !=0"
If you don't mind using lodash, then this is a handy utility library for your javascript, which can help with tasks like this.
var objHodUserDataWithoutBlanks = _.filter(objHodUserData, function(n) {
return n.user_name != "";
});
The above will filter out entries that have a blank username. Then your ng-repeat can instead repeat over this object without blanks: objHodUserDataWithoutBlanks.
Edit: Alternate method using only angularjs:
Add an angular filter:
myApp.filter('nonBlankOnly', function() {
return function( items) {
var filtered = [];
angular.forEach(items, function(item) {
if(item.user_name != "") {
filtered.push(item);
}
});
return filtered;
};
});
Then apply the filter in your controller:
function myCtrl($scope, $filter)
{
$scope.objHodUserDataWithoutBlanks = $filter('nonBlankOnly')(objHodUserData);
}
And repeat through filtered items:
<tr ng-repeat="user in objHodUserDataWithoutBlanks">
Maybe you can use de ng-show to check if there is an existing user, something like:
<tr ng-repeat="user in objHodUserData ">
<td ng-show="user">{{$index+1}}</td>
<td ng-show="user">{{user.user_name}}</td>
<td ng-show="user">{{user.email}}</td>
<td ng-show="user">{{user.mob_no}}</td>
<td ng-show="user">{{user.login_name}}</td>
or if you prefer to hide the entire row, put the ng-show on the <tr> element.
<tbody id="detailsstockid">
<tr ng-repeat="user in objHodUserData " ng-show="user">
<td>{{$index+1}}</td>
<td>{{user.user_name}}</td>
<td>{{user.email}}</td>
<td>{{user.mob_no}}</td>
<td>{{user.login_name}}</td>
<td ng-if="user.user_status==1">Enable</td>
<td ng-if="user.user_status==0">Disable</td>
<td>
<a ui-sref='hod.user'>
<input type='button' class='btn btn-xs btn-green' value='Edit' ng-click="editUserData(user.user_id)" >
</a>
</td>
<td>
<a ui-sref='hod.user'>
<input type='button' class='btn btn-xs btn-red' value='Delete' ng-click="deleteUserData(user.user_id);" >
</a>
</td>
</tr>
</tbody>

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

AngularJS: post data to server

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.

Categories

Resources