Calling async function in ng-repeat - angularjs

I am trying to call an async function in ng-repeat. I am sure that this is not the right way to do this but would like to know what is the correct 'Angular way'
<tr ng-repeat="app in multipleApps">
<td><h4> {{ app.Name }} </h4></td>
<td><h4> {{ getActivationDate(app.Name) }} </h4></td>
</tr>
In the controller the getActivationDate calls a factory function which returns a promise. So I need to know how to use this function in the ng-repeat.
$scope.getActivationDate = function(name)
{
Service.getActivationDate(appName)
.then(function(response) {
var ts = response.activated_at;
var date = new Date(ts *1000);
console.log(date.toDateString());
return date.toDateString();
},
function(error)
{
$scope.error = true;
});
}
Service.getMultipleApps()
.then(function(data) {
$scope.$apply(function () {
$scope.multipleApps = data;
});
});
Thanks

You can try with:
<tr ng-repeat="app in multipleApps" ng-init="getActivationDate(app)">
<td><h4> {{ app.Name }} </h4></td>
<td><h4> {{ app.activationDate }} </h4></td>
</tr>
And in the getActivationDate function:
$scope.getActivationDate = function(app) {
Service.getActivationDate(app.name)
.then(function(response) {
var ts = response.activated_at;
var date = new Date(ts *1000);
app.activationDate = date;
},
// ...
};

Related

Array Push not working with Real Time

I'm using Pusher for Angular Webapp for Real Time Application. I need add to array products a new item when other add a item from form in other session. In my sessiĆ³n it's works. In another session the data obtained if it is added to the array but not shown in the ng-repeat.
Controller:
.controller('MainCtrl', ['$scope','Products',function($scope,Products) {
$scope.products = Products.getAll();
var pusher = new Pusher('MY KEY', {
encrypted: true
});
$scope.addProduct = function(product){
Products.addProduct(product);
}
var callback = function(data) {
$scope.products.push(data.NewProduct);
console.log($scope.products);
};
var channel = pusher.subscribe('products');
channel.bind('addProduct', callback);
}]);
View:
<tbody>
<tr ng-repeat="product in products track by product.id">
<td >{{product.name}}</td>
<td>{{product.unity}}</td>
<td>{{product.price}}</td>
<td>
<button>
Edit
</button>
<button>
Delete
</button>
</td>
</tr>
</tbody>
$evalAsync Executes the expression on the current scope at a later point in time.
So add $evalAsync to callback function in your code
.controller('MainCtrl', ['$scope','$evalAsync','Products',function($scope,$evalAsync, Products) {
$scope.products = Products.getAll();
var pusher = new Pusher('MY KEY', {
encrypted: true
});
$scope.addProduct = function(product){
Products.addProduct(product);
}
var callback = function(data) {
$scope.products.push(data.NewProduct);
console.log($scope.products);
};
var channel = pusher.subscribe('products');
channel.bind('addProduct', $evalAsync(callback));
}]);
I did it like this:
var callback = function(data) {
$scope.$apply(function(){
$scope.products.push(data.Producto);
});
console.log($scope.products);
};

$scope variable is undefined in post

I have AngularJS repeat biaya in data_biaya that I have from JSON.
When I ng-click="simpan_biaya(data_biaya)", why is the data posting undefined?
<input type="button" ng-click="simpan_biaya(data_biaya)" value="Simpan"/>
<tr ng-repeat="biaya in data_biaya | filter:{tahapan_id : 10}" >
<td>{{$index+1}}</td>
<td><span >{{biaya.tanggal_transaksi}}</span></td>
<td><span>{{biaya.uraian}}</span></td>
<td><span>{{biaya.pihak_nama}}</span></td>
<td><span >{{data_biaya[$index].pemasukan}}</span></td>
<td><span>{{biaya.pengeluaran}}</span></td>
<td>{{biaya.sisa}}</td>
<td><span >{{biaya.keterangan}}</span></td>
</tr>
JavaScript
var datanya=[
{"id":"23713","id_pembiayaan":"1","perkara_id":"7200","tahapan_id":"10","kategori_id":"1","jenis_biaya_id":"1","pihak_id":null,"pihak_ke":null,"urutan":"1","jenis_transaksi":"1","tanggal_transaksi":"2016-05-26","uraian":"Panjar Biaya Perkara","pemasukan":1000000,"pengeluaran":0,"jumlah":1000000,"sisa":1000000,"keterangan":null,"pihak_nama":"Penggugat"},
{"id":"23714","id_pembiayaan":"1","perkara_id":"7200","tahapan_id":"10","kategori_id":"11","jenis_biaya_id":"61","pihak_id":null,"pihak_ke":null,"urutan":"2","jenis_transaksi":"-1","tanggal_transaksi":"2016-05-26","uraian":"Biaya Pendaftaran\/PNBP","pemasukan":0,"pengeluaran":"30000.00","jumlah":"30000.00","sisa":970000,"keterangan":null,"pihak_nama":"Penggugat"}
];
var app = angular.module('jurnalApp', []);
app.controller('jurnalCtrl', function($scope,$http) {
$scope.data_biaya = [];
$scope.searchClick = function (data) {
$scope.$apply(function(){
$scope.data_biaya=datanya;
});
};
$scope.simpan_biaya = function(data){
var post_data = data;
$.post("<?php echo base_url().'all_jurnal/set_jurnal_biaya';?>", post_data)
.done(function(json){
});
}
angular.element(document).ready(function () {
$scope.searchClick();
});
});
Here: plunker
Try this:
<input type="button" ng-click="simpan_biaya(data_biaya)" value="Simpan"/>
DEMO
Based on the attached screenshot, you should pass JSON data, convert the data to JSON before passing:
var dataJson=angular.toJson(post_data);
you should use that:
var post_data = data; var dataJson=angular.toJson(post_data); $.post("
<?php echo base_url().'all_jurnal/set_jurnal_biaya';?>", dataJson ) .done(function(json){ });

Angular Two Way Data Binding Not Working While Using HTTP

I am using ControllerAs in angular with ui.router, I have an API in PHP when I call the API and set the scope variable by vm approach for templates then it works accordingly and when I want to delete some record set
and update the vm.servers variable again then template not change according to the newly updated object.
function serverController( server, $state, $rootScope, $scope)
{
var vm = this;
vm.delete = function(server_id) {
vm.loader = false;
server.delete('server/' + server_id)
.then(
function(response){
if(response.status === 200 && !response.data.status) {
alert(response.data.message);
} else if(response.status === 200 && response.data.status){
server.setRootScope().then(
function(){
vm.servers = $rootScope.servers;
$state.go($state.current, {}, {reload: true});
}
);
}
}, function(response) {
if(response.status === 401) {
$state.go('login');
}
}
);
};
if($rootScope.servers == undefined) {
server.get('server')
.then(
function (response) {
if (response.status === 200) {
vm.servers = response.data;
$rootScope.servers = {};
angular.forEach(response.data, function (val) {
if('running' === val.status) {
val['serverState'] = true;
} else {
val['serverState'] = false;
}
$rootScope.servers[val.id] = val;
});
}
},
function (response) {
if (response.status === 401) {
$state.go('login');
}
});
} else {
vm.servers = $rootScope.servers;
}
}
Template File.
<table class="table movietable" width="70%" border="1">
<tr ng-repeat="server in serverModel.servers">
<td width="85%">
<table>
<tr>
<td><b>Server Label: </b> {{server.label}}</td>
</tr>
<tr>
<td>Status: {{server.status}}</td>
</tr>
<tr>
<td>Created At: {{server.created_at}}</td>
</tr>
</table>
</td>
</tr>
</table>
I look your code. I found a problem that,
You are not updating the vm.servers with
the response data. As the values in $rootScope.servers might
be older. So with every delete function call you will have to either update the $rootScope.servers or vm.servers with new data.
I have create a small demo from your code, hope it will help you
identify the problem. In this demo I have first load the data in table
after this, on a button click deleting the record by id and updating
the vm.servers.
My Controller
.controller('Controller',['$rootScope', function($rootScope) {
var vm =this;
vm.customer = {
name: 'Naomi',
address: '1600 Amphitheatre'
};
vm.delete = function(server_id) {
vm.loader = false;
// added some value to $rootScope.servers or you can update it with response data. This is where you will need to update your logic.
$rootScope.servers = [
{ id: 1,
name: 'Naomi1',
address: '1600 Amphitheatre1'
},
{
id: 2,
name: 'Naomi2',
address: '1600 Amphitheatre2'
}
];
angular.forEach($rootScope.servers, function(value,key) {
if(value.id == server_id) {
$rootScope.servers.splice(key,1);
}
});
console.log($rootScope.servers);
//Here I have assign new $rootScope.servers.
vm.servers = $rootScope.servers;
};
var val = {};
vm.init = function() {
vm.servers = [{
id: 1,
name: 'Naomi1',
address: '1600 Amphitheatre1'
},{
id: 2,
name: 'Naomi2',
address: '1600 Amphitheatre2'
}];
$rootScope.servers = {};
val['serverState'] = true;
$rootScope.servers[val.id] = val;
}
vm.init();
}])
index.html
<div ng-controller="Controller as vm">
<table class="table movietable" width="70%" border="1">
<tr>
<td width="85%">
<table>
<tr ng-repeat="server in vm.servers">
<td><b>Server Label: </b> {{server.name}}</td>
<td>Status: {{server.address}}</td>
<td><button ng-click="vm.delete(server.id);">Delete</button></td>
</tr>
</table>
</td>
</tr>
</table>
</div>
Hope this will help you !
Cheers,
Jimmy

Factory not providing proper values to controller

In my angular js project factory is not providing values to the controller as needed. I always get empty result in view. When i logged in browser using console.log() all i can see in console is :
[object Object],[object Object],[object Object]. I am stuck at this. Tried many things but nothing worked.
This is my controller code:
var controllers = {};
controllers.ProductController = function ($scope, $route, $routeParams, $location, ProductFactory) {
$scope.products = [];
var init = function () {
$scope.products = ProductFactory.getProducts();
console.log('got products in controller');
console.log($scope.products)
};
var initProductEdit = function () {
var code = $routeParams.code;
if (code = undefined) {
$scope.currentProduct = {};
}
else
{
$scope.currentProduct = ProductFactory.loadProductByCode(code);
}
};
$scope.$on('$viewContentLoaded', function () {
var templateUrl = $route.current.templateUrl;
if (templateUrl == '/Partials/ProductEdit.html') {
initProductEdit();
}
else if (templateUrl == '/Partials/ProductList.html')
{
var code = $routeParams.code;
if(code!=undefined)
{
$scope.deleteProduct(code);
}
}
});
init();
$scope.saveProduct = function () {
ProductFactory.saveProduct($scope.currentProduct);
$location.search('code', null);
$location.path('/');
};
$scope.deleteProduct = function (code) {
ProductFactory.deleteProduct(code);
$location.search('code', null);
$location.path('/');
};
};
angSPA.controller(controllers);
This is my factory code:
angSPA.factory('ProductFactory', function () {
var products = [
{ code: 1, name: 'Game of Thrones', description: 'Series' }
{ code: 2, name: 'DmC', description: 'Game' },
{ code: 3, name: 'Matrix', description: 'Movie' },
{ code: 4, name: 'Linkin Park', description: 'Music Band' }];
var factory = {};
console.log('initializing factory');
factory.getProducts = function () {
console.log('factory now providing products');
return products;
};
factory.loadProductByCode = function (code) {
var product;
for (var i = 0; i < products.length; i++) {
if (products[i].code == code) {
product = products[i];
return product;
}
}
};
factory.saveProduct = function (product) {
products.push(product);
console.log('factory saved product');
};
factory.deleteProduct = function (code) {
var product = factory.loadProductByCode(code);
if (product != null) {
products.remove(product);
console.log('factory deleted product');
}
};
console.log('returning factory');
return factory;
});
This is my view:
<div class="container">
<h2 class="page-title">Product Listing</h2>
<div class="searchbar">
<ul class="entity-tabular-fields">
<li>
<label>Search: </label>
<span class="field-control">
<input type="text" data-ng-model="filter.productName" />
</span>
<label></label>
</li>
</ul>
</div>
<h2>Add New Product</h2>
<table class="items-listing">
<thead>
<tr>
<th>Code</th>
<th>Name</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td data-ng-repeat="product in products|filter:filter.productName"></td>
<td>{{product.code}}</td>
<td>{{product.name}}</td>
<td>{{product.description}}</td>
<td>Delete</td>
</tr>
</tbody>
</table>
</div>
My routing function:
angSPA.config(function ($routeProvider) {
$routeProvider
.when(
'/',
{
controller: 'ProductController',
templateUrl: 'Partials/ProductList.html'
})
.when(
'/ProductEdit',
{
controller: 'ProductController',
templateUrl: 'Partials/ProductEdit.html'
})
.otherwise({
redirectTo: '/'
});
console.log('routing done');
});
Change your htmt given
var angSPA = angular.module('angSPA', []);
angSPA.controller("ProductController", function($scope, ProductFactory) {
$scope.products = [];
var init = function() {
$scope.products = ProductFactory.getProducts();
console.log('got products in controller');
console.log($scope.products + "")
};
init();
});
angSPA.factory('ProductFactory', function() {
var products = [
{code: 1, name: 'Game of Thrones', description: 'Series'},
{code: 2, name: 'DmC', description: 'Game'},
{code: 3, name: 'Matrix', description: 'Movie'},
{code: 4, name: 'Linkin Park', description: 'Music Band'}];
var factory = {};
console.log('initializing factory');
factory.getProducts = function() {
console.log('factory now providing products');
return products;
};
factory.loadProductByCode = function(code) {
var product;
for (var i = 0; i < products.length; i++) {
if (products[i].code == code) {
product = products[i];
return product;
}
}
};
factory.saveProduct = function(product) {
products.push(product);
console.log('factory saved product');
};
factory.deleteProduct = function(code) {
var product = factory.loadProductByCode(code);
if (product != null) {
products.remove(product);
console.log('factory deleted product');
}
};
console.log('returning factory');
return factory;
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js"></script>
<body ng-app="angSPA" ng-controller="ProductController">
<div class="container">
<h2 class="page-title">Product Listing</h2>
<div class="searchbar">
<ul class="entity-tabular-fields">
<li>
<label>Search: </label>
<span class="field-control">
<input type="text" data-ng-model="filter.productName" />
</span>
<label></label>
</li>
</ul>
</div>
<h2>Add New Product</h2>
<table class="items-listing">
<thead>
<tr>
<th>Code</th>
<th>Name</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr data-ng-repeat="prod in products|filter:filter.productName">
<td ></td>
<td>{{prod.code}}</td>
<td>{{prod.name}}</td>
<td>{{prod.description}}</td>
<td>Delete</td>
</tr>
</tbody>
</table>
</div>
Your ng-repeat directive should be on the tr element and not the td.
<tr data-ng-repeat="product in products|filter:filter.productName">
Not the cause of your problem, but to log in a service or controller, you can use the $log service and stringify to serialize your objects.
$log.debug(JSON.stringify($scope.products));
Looking at your code, you do $scope.products = [] right at the beginning. This will make angular watch the empty array.
In your init function you assign the products array to $scope.products. But as angular is still watching the initial array it will not be aware of the change.
The solution is to delete the initial assignment $scope.products = [] and make sure to alter the original array but never set it to a new array.
BTW: you could do console.log(JSON.stringify($scope.products)) to get better log information.

RestAngular Put request in AngularJs

How can I make a put request in RestAngular?
This is what I tried.
facUpdatePartner: function (partner)
{
var url = "UpdatePartner";
var result = Restangular.one(url);
return result.put(partner);
}
I don't know you full code but should is something like this:
facUpdatePartner: function (partner)
{
return partner.put();
}
the partner need to come from a previous getOne or a get with Restangular. For example:
Controller:
vm.getCategories = function () {
Category.get().then(function (categories) {
vm.categories = categories;
});
};
vm.getCategories();
vm.update = function(category){
category.put().then(function(result){
alert('UPDATED!');
}).catch(function(err){
alert('ERROR!');
});
};
HTML:
...
<tr ng-repeat="category in vm.categories">
<td>
<input type="text" ng-model="category.name">
</td>
<td>
<button type="button" ng-click="vm.update(category)">
</td>
</tr>
....

Resources