RestAngular Put request in AngularJs - 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>
....

Related

AngularJS ng-click not responding when clicked

I know there is alot of questions about this topic out there, but could not find any solution to my problem. My code:
UPDATE
$scope.openOne = function (id) {
ImageService.getDetails(id).then(function (data) {
$scope.imageDetail = data;
}).catch(function (e) {
var message = [];
});
}
function getAllImages() {
ImageService.getImages().then(function (value) {
$scope.images = value;
var items = [];
$(value).each(function () {
var url = "https://someUrl/" + this.Image[0];
console.log(url);
items.push(`
<tr>
<td><button id="button" ng-click="openOne(${this._id})">${this.ImageName}</button></td>
<td>${this.ImageCategory}</td>
<td>
<img style="width:30%;" ng-src="${url}" alt="The Image is missing">
</td>
</tr>
`);
});
$("#body").append(items.join(''));
}).catch(function (e) {
var message = [];
}).finally(function (e) {
});
}
I am creating the button in in the controller and then appending it to the DOM.
Does anybody see the error? When I click the button nothing happens.
Approach is all wrong.
The fundamental principal in angular is let your data model drive the view and let angular compile that view from templates
A more typical set up would pass your images array to ng-repeat in the view:
Controller:
function getAllImages() {
ImageService.getImages().then(function (value) {
$scope.images = value;
});
}
View:
<tr ng-repeat="img in images track by $index">
<td><button id="button" ng-click="openOne(img.id)">{{img.ImageName}}</button></td>
<td>{{img.ImageCategory}}</td>
<td>
<img style="width:30%;" ng-src="{{img.url}}" alt="The Image is missing">
</td>
</tr>
You need to add $compile service here, that will bind the angular directives like ng-click to your controller scope. For example
app.controller('yourController', function($scope,$compile) {
var button = '<button id="button" ng-click="openOne(${this._id})">${this.ImageName}</button>';
items.push(button);
$("#body").append(items.join(''));
var temp = $compile(button)($scope);
$scope.openOne = function(){
alert('Yes Click working at dynamically added element');
}
});

$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){ });

Calling async function in ng-repeat

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;
},
// ...
};

Add, Remove & Update specific data In JSON in AngularJS

I have pulled data from json file. Now its displayed over DOM.
On HTML Page, I have three option 1) Edit Data 2) Delete Particular Data & 3) Add New Data.
How to perform this using AngularJS Code? i.e. on editing name, it should update my JSON object. On Deleting row, it should delete that row in JSON data. and also If I click on Add New, then entered data will be added to JSON.
My Code is as below.
Importing data through json file and displaying on DOM
.controller('MainCtrl', function ($scope, $http) {
$http.get('data/home.json').
success(function(data, status, headers, config) {
$scope.details = data;
}).
error(function(data, status, headers, config) {
// log error
});
});
Output of this code is correct as below image.
JSON Object as below.
{
"status":"success",
"adformat":[
{
"adformat_id":1,
"name":"Format 1",
"size":"300x250"
},
{
"adformat_id":2,
"name":"Format 2",
"size":"320x250"
},
{
"adformat_id":3,
"name":"Format 3",
"size":"320x480"
}
]
}
I would do it like this:
MainCtrl.js
(function () {
'use strict';
angular
.module('app')
.controller('MainCtrl', MainCtrl);
MainCtrl.$inject = ['$scope', 'MainFactory'];
function MainCtrl($scope, MainFactory) {
$scope.details = MainFactory.details;
function init() {
MainFactory.get();
}
init();
$scope.detailsModel = {
"adformat_id": 1,
"name": "Format 1",
"size": "300x250"
};
$scope.add = function () {
$scope.details.push($scope.detailsModel);
};
$scope.delete = function (index) {
$scope.details.splice(index, 1);
};
$scope.edited = -1;
$scope.editedModel = {
"adformat_id": 0,
"name": "",
"size": ""
};
$scope.edit = function (index) {
$scope.edited = index;
};
$scope.finishEdit = function (index) {
$scope.details[index] = $scope.editedModel;
$scope.edited = -1;
};
}
})();
MainFactory.js
(function () {
'use strict';
angular
.module('app')
.factory('MainFactory', MainFactory);
MainFactory.$inject = [];
function MainFactory() {
var self = this;
self.details = [];
self.get = $http.get('data/home.json')
.then(function (response) {
self.details = response.data;
}).catch(function (error) {
// log error
});
return self;
}
})();
index.html
<div ng-app="app">
<div ng-controller="MainCtrl">
<table>
<tbody>
<tr ng-repeat="details in detail">
<!-- show-->
<td ng-hide="edited === $index">{{detail.adformat_id}}</td>
<td ng-hide="edited === $index">{{detail.name}}</td>
<td ng-hide="edited === $index">{{detail.size}}</td>
<td ng-hide="edited === $index">
<button ng-click="edit($index)">Edit</button>
<button ng-click="delete($index)">Detele</button>
</td>
<!-- Edit-->
<td ng-show="edited === $index">{{detail.adformat_id}}</td>
<td ng-show="edited === $index"><input type="text" ng-model="editedModel.name"></td>
<td ng-show="edited === $index"><input type="number" ng-model="editedModel.size"></td>
<td ng-show="edited === $index">
<button ng-click="finishEdit($index, editedModel)">Save</button>
<button ng-click="delete($index)">Detele</button>
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>
<button ng-click="add()">Add</button>
</td>
</tr>
</tfoot>
</table>
</div>
</div>
It is just prototype, not tested, but it should help you to understand idea o two way binding in angular.
Here is my approach to this requirement. Let me know if any further improvement can be added. The entire code can be found at the below URL:
Angular Save, Update and Delete
The sample screenshots from the code can be found here...
controller:
'use strict';
function MainController($scope, SharedService, ngDialog) {
$scope.account_type_selected = "Savings";
$scope.sharedService = SharedService;
$scope.savingsMain = [];
$scope.checkingsMain = [];
$scope.addToCheckingsAccounts = {};
$scope.addToSavingsAccounts = {};
$scope.setAccountType = function (type) {
if (type === "allAccounts") {
$scope.showSavings = true;
$scope.showCheckings = true;
} else if (type === "savingsAccounts") {
$scope.showSavings = true;
$scope.showCheckings = false;
} else if (type === "checkingAccounts") {
$scope.showSavings = false;
$scope.showCheckings = true;
}
$scope.account_type_selected = type;
};
$scope.$watch('savingsMain', function ($scope) {
return $scope.savingsMain;
});
$scope.selectedAccountType = function (showAccount) {
console.log(showAccount);
if (showAccount === "Savings") {
$scope.sharedService.accountType = "Savings";
} else {
$scope.sharedService.accountType = "Checkings";
}
};
$scope.saveAccounts = function () {
if ($scope.sharedService.accountType === "Savings") {
$scope.addToSavingsAccounts = {
"account_type": $scope.sharedService.accountType,
"amount": $scope.sharedService.amount,
"date": $scope.sharedService.date,
"maturity": $scope.sharedService.maturity
};
$scope.showSavings = true;
$scope.savingsMain.push($scope.addToSavingsAccounts);
} else {
$scope.addToCheckingsAccounts = {
"account_type": $scope.sharedService.accountType,
"amount": $scope.sharedService.amount,
"bic": $scope.sharedService.BIC,
"iban": $scope.sharedService.IBAN
};
$scope.showCheckings = true;
$scope.checkingsMain.push($scope.addToCheckingsAccounts);
}
ngDialog.close();
};
$scope.deleteDataFromSharedService = function (accountType, item) {
if (accountType === "Savings") {
$scope.savingsMain = _.without($scope.savingsMain, _.findWhere($scope.savingsMain, { date: item }));
} else if (accountType === "Checkings") {
$scope.checkingsMain = _.without($scope.checkingsMain, _.findWhere($scope.checkingsMain, { bic: item }));
}
};
$scope.closeDialog = function () {
ngDialog.close();
};
$scope.accountTypeModel = [];
$scope.prop = {
"type": "select",
"name": "account_type",
"value": $scope.sharedService.accountType,
"accountTypeData": ["Savings", "Checkings"]
};
}
<form ng-controller="MainController">
<div class="page-header">
<h1>Angular-Save-Update-Delete</h1>
</div>
<div class="content-wrapper">
<div class="sidebar">
<table>
<tbody>
<tr>
<td>
<button ng-click="setAccountType('allAccounts')" ng-model="allAccounts" class="ng-pristine ng-untouched ng-valid ng-empty">All</button>
</td>
</tr>
<tr>
<td>
<button ng-click="setAccountType('savingsAccounts')" ng-model="savingsMain" class="ng-pristine ng-valid ng-not-empty ng-touched">Savings</button>
</td>
</tr>
<tr>
<td>
<button ng-click="setAccountType('checkingAccounts')" ng-model="checkingsMain" class="ng-pristine ng-untouched ng-valid ng-not-empty">Checkings</button>
</td>
</tr>
<tr>
<td>
<button class="create-account-btn-class"
type="button"
ng-dialog="app/views/create-account-template.html"
ng-dialog-data=""
ng-dialog-class="ngdialog-theme-default"
ng-dialog-scope="this"
plain=false
showClose=true
closeByDocument=true
closeByEscape=true
ng-dialog-show-close="false">New Account</button>
</td>
</tr>
</tbody>
</table>
</div>
<div class="right-content">
<div id="savingsTemplate" templateurl="app/views/savings.html" ng-show="showSavings" include-template=""></div>
<div id="checkingsTemplate" templateurl="app/views/checkings.html" ng-show="showCheckings" include-template=""></div>
</div>
</div>
</form>

Angularjs Service does not work

I define a Service to share a variable between two controllers, but when i set the variable in a controller and then get this from another controller it does not get the correct value , this is the service:
App.service("ProductService", function () {
var productTotalCount = {};
return {
getproductTotalCount: function () {
return productTotalCount;
},
setproductTotalCount: function (value) {
productTotalCount = value;
}
}
});
and this is the controller which i set productTotalCount:
App.controller("ProductController", function ($scope, $http, $rootScope, ProductService) {
$scope.GetAllProducts = $http.get("GetAllProductsInformation").success(function (data) {
$rootScope.Products = data.Data;
ProductService.setproductTotalCount(data.TotalCount); // i set productTotalCount here and it's value became 19
});
$scope.editProduct = function (data) {
$scope.model = data;
$rootScope.$broadcast('modalFire', data)
}
});
and when i get the productTotalCount in this controller it return object instead of 19 :
App.controller('Pagination', function ($scope, ProductService) {
debugger;
$scope.totalItems = ProductService.getproductTotalCount(); // it should return 19 but return object!!
$scope.currentPage = 1;
$scope.itemPerPage = 8;
});
what is the problem?
EDIT: this is the html, it may help :
<div ng-controller="ProductController" ng-init="GetAllProducts()">
<div class="row" style="margin-top:90px" ng-show="!ShowGrid">
<article class="widget">
<header class="widget__header">
<div class="widget__title">
<i class="pe-7s-menu"></i><h3>ProductList</h3>
</div>
<div class="widget__config">
<i class="pe-7f-refresh"></i>
<i class="pe-7s-close"></i>
</div>
</header>
<div class="widget__content table-responsive">
<table class="table table-striped media-table">
<thead style="background-color:rgba(33, 25, 36,0.1)">
<tr>
<th style="width:40%">edit</th>
<th style="width:30%">Price</th>
<th style="width:30%">ProductName</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="product in Products">
#*<td>{{product.ProductDescription}}</td>*#
<td>
<input class="btn btn-default" style="padding: 14px;background: rgba(0, 0, 0, 0.2)" type="submit" value="Edit" ng-click="editProduct(product)" />
</td>
<td>{{product.Price}}</td>
<td>{{product.ProductName}}</td>
</tr>
</tbody>
</table>
</div>
</article>
</div>
</div>
<div ng-controller="Pagination">
<pagination total-items="totalItems" ng-change="pageChanged()" previous-text="Before" next-text="Next" first-text="First"
last-text="Last" ng-model="currentPage" items-per-page="itemPerPage" max-size="maxSize" class="pagination-sm" boundary-links="true"></pagination>
</div>
From the controller names, I bet the Pagination and ProductController controllers are both instantiated more or less at the same time, BEFORE invoking the .setproductTotalCount() method. If that is the case, then because you are treating the productTotalCount variable as a primitive type (instead of an object) after setting it, the changes do not get reflected between the controllers.
Try the following:
// Change the service to:
App.service("ProductService", function () {
var productTotalCount = {};
return {
getproductTotalCount: function () {
return productTotalCount;
},
setproductTotalCount: function (value) {
productTotalCount.value = value;
}
}
});
// In Pagination controller:
App.controller('Pagination', function ($scope, ProductService) {
debugger;
$scope.totalItems = ProductService.getproductTotalCount(); // this will still be an empty object initially, but when the value is updated in the service, the $scope.totalItems will also be updated
$scope.currentPage = 1;
$scope.itemPerPage = 8;
// this should confirm that changes are being propagated.
$scope.$watch('totalItems', function(newVal) {
console.log('totalItems updated. New Value:', newVal);
});
// NOTE: Keep in mind that the real productTotalCount will be stored as $scope.totalItems.value;
});
---- EDIT ----
Per your comment below, it proves that the solution above DOES work. To prove it, change:
$scope.$watch('totalItems', function(newVal) {
console.log('totalItems updated. New Value:', newVal);
});
to
$scope.$watch('totalItems', function(newVal) {
console.log('totalItems updated. New Value:', newVal);
console.log($scope.totalItems);
});
At that point, you should see that $scope.totalItems has been updated to:
{ value: 19 };
The issue may be how you're declaring your variable in your service. Because it's a local variable in the function rather than returned object, I believe it will be creating a new variable for each time you inject the service as a dependency. Try making the variable a member of the returned object. E.g.
App.service("ProductService", function () {
return {
productTotalCount: 0,
getproductTotalCount: function () {
return this.productTotalCount;
},
setproductTotalCount: function (value) {
this.productTotalCount = value;
}
}
});

Resources