Get Value of column by API in angular - angularjs

I want to get status value from API in my grid made in angular js. Below is the code, I applied in my view file:
<tr ng-repeat="item in list">
<td>{{item.id}}</td>
<td class="text-center" ng-init="statusUpdate(item.id ,$index)">
</td>
<td>{{myVar[$index]}}</td>
</tr>
Then in my controller I added:
app.controller('MerchantController', function ($scope, MerchantService, Alert, toaster) {
$scope.statusUpdate = function (id, index) {
var api = MerchantService.statusUpdate(id, index).then(function (response) {
console.log($scope.myVar[index]);
$scope.myVar[index] = response.data;
console.log($scope.myVar[index]);
});
};
});
In my service file, I added:
app.service('MerchantService', function(API, $stateParams, $q,$http) {
this.statusUpdate = function(item,index) {
return $http({
url: 'http://10.10.10.7/petca_magento/integration/vendor/vendor/id/' + item,
method: "GET",
});
};
});
I want to get of status field dynamically based on the user id in {{myVar[$index]}}

Related

angularjs not updaing propeties when promises used

I am using service to get JSON object using promises. It is then converted into array and assign to a property which is in $scope object. The problem is that array is not getting updated or any properties inside promise then() method.
Controller
var searchController = function ($scope, $SPJSOMService) {
$scope.myName = "old name";
$scope.getUsers = function ($event) { //called on button click
$event.preventDefault();
var queryText = "test user";
$SPJSOMService.getUsers(queryText)
.then(function myfunction(users) {
$scope.userCollection = JSON.parse(JSON.stringify(users)).d.results;
// $scope.$apply(); this line throwing error. $rootScope in progress
$scope.myName = "new name"; //not getting updated
}, function (reason) {
alert(reason);
});
};
};
Service
var SPJSOMService = function ($q, $http, $rootScope) {
this.getUsers = function (userToSerach) {
var deferred = $q.defer();
$http({
url:'some url',
method: "GET",
headers: {
"accept": "application/json;odata=verbose",
"content-Type": "application/json;odata=verbose"
}
})
.success(function (data, status, headers, config) {
deferred.resolve(data); //successfully return data
})
.error(function (data, status, headers, config) {
deferred.reject(data);
});
return deferred.promise;
};
};
Updated
index.html
<div ng-include="'Search.html'">
</div>
<div ng-include="'searchResults.html'"></div>
search.html
<div id="containerDiv" ng-controller="searchController as search">
<input class="button" type="button" ng-click="getUsers($event);" value="Search" id="btnSearch" />
</div>
searchResults.html
<div ng-controller="searchResultController as result">
<table >
<thead>
<tr>
<th>Name</th>
<th>EMail</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in userCollection">
<td>{{$index}} {{item.userName}}</td>
<td>{{$index}} {{item.userEmail}}</td>
</tr>
</tbody>
</table>
</div>
So search.html returns the data by calling the service and I am trying to pass it to the page namely searchResults.html which have its own controller.
$scope.users = $scope.userCollection;
Service class correctly returning data, but the problem is inside then(), which is not updating $scope.userCollection, hence UI is not getting updated.
Please help me out, what am I missing here.
In angular controllers can bind to the view in two ways:
"controller as"
through scope
It looks you are using the "controller as" flavor here...
<div ng-controller="searchResultController as result">
Refer to https://docs.angularjs.org/api/ng/directive/ngController for more information.
Change your controller code to:
var searchController = function ($scope, $SPJSOMService) {
//note use of "this" instead of "$Scope"
var _this = this;
_this.myName = "old name";
_this.getUsers = function ($event) { //called on button click
$event.preventDefault();
var queryText = "test user";
$SPJSOMService.getUsers(queryText)
.then(function myfunction(users) {
_this.userCollection = users.d.results; //You don't need JSON.parse not JSON.stringify
_this.myName = "new name";
}, function (reason) {
alert(reason);
});
};
};
and in your view use the controller "alias":
<div ng-controller="searchResultController as result">
...
<tr ng-repeat="item in result.userCollection">
...
You have to push it to the new array I think. Have you tried this in your then statement?
$scope.myName.push("new name");
It should put it in the existing array. Let me know if it works.

Pass the object from angularjs controller to rest api

hi i am creating a application with Angularjs,REST service with spring. i want to pass the object from angulajs url to rest service , but it does work, please any one help me, my jsp page code is like below,
<html ng-app="studentApp">
<body>
<div ng-controller="studentController">
<table border = "0">
<tr>
<td>Enter first name:</td>
<td><input type = "text" ng-model = "student.firstName"></td>
</tr>
<tr>
<td>Enter last name: </td>
<td>
<input type = "text" ng-model = "student.lastName">
</td>
</tr>
</table>
</div>
</body>
</html>
and my angularjs code is,
var studentApp = angular.module("studentApp", []);
studentApp.config(['$httpProvider', function ($httpProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
}]);
studentApp.controller("studentController", [ '$scope', '$http',
function($scope, $http) {
$scope.toggle=true;
var urlBase="http://localhost:8080/studentweb/";
$scope.insertStudent = function inserStudent() {
$http({
method : 'POST',
url : urlBase+'/Student/insert',
data: {student:data}
}).success(function(data, status, headers, config) {
$scope.student=data;
$scope.toggle='!toggle';
}).error(function(data, status, headers, config) {
alert( "failure1");
});
and my rest service is,
public class StudentController
{
#RequestMapping(value="/Student/insert",method = RequestMethod.POST ,params= {"student"})
public String insertStudent(#RequestParam("student") StudentVO student) throws ParseException {
student.setFirstName(student.getFristName());
student.setLastName(student.getLstName());
studentcontrol.addStudent(student);
return "";
}
}
} ])
The problem is that you "usrlBase" variable has "student/" extra as you are already calling your Student controller in
url : urlBase+'/Student/insert'
Hence the complete URL becomes something like
http://localhost:8080/student//Student/insert whereas it should be something like:
http://localhost:8080/Student/insertStudent
Update:
Below is an absolutely fine working example with a sample restful service you had some brackets missing in your code. Please go through the below code and get back to me if required.
<html ng-app="studentApp">
<div ng-controller="studentController">
<table border="0">
<tr>
<td>Enter first name:</td>
<td><input type="text" ng-model="student.FirstName"></td>
</tr>
<tr>
<td>Enter last name: </td>
<td>
<input type="text" ng-model="student.LastName">
</td>
</tr>
</table>
</div>
Script:
var studentApp = angular.module("studentApp", []);
studentApp.config(['$httpProvider', function ($httpProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
}]);
studentApp.controller("studentController", ['$scope', '$http',
function ($scope, $http) {
$scope.toggle = true;
//var urlBase = "http://localhost:8080/student/";
// $scope.insertStudent = function () {
debugger;
$http({
method: 'GET',
url: 'http://services.odata.org/V4/Northwind/Northwind.svc/Employees(1)?$format=json',
// data: { student: data }
}).success(function (data, status, headers, config) {
debugger;
$scope.student = data;
$scope.toggle = '!toggle';
}).error(function (data, status, headers, config) {
debugger;
alert("failure1");
});
// }
}]);

send the data from a table to an input text with angularjs

I tried to get the value from a table to my input text,this is my try:
this is the first page that contains the list of clients:
clients.html
<div id="ng-app" ng-controller="PostController">
<table class="table table-striped table-bordered" style="text-align:center" id="table" > <!--onClick="select()"-->
<thead>
<th align="center">Référence</th><th align="center">Nom</th><th align="center">Prenom</th><th align="center">Email</th><th align="center">Adresse Facturation</th><th align="center" colspan="2">Actions</th>
</thead>
<tbody>
<tr ng-repeat="post in posts | filter:posts.nom" >
<td align="center">{{post.id}}</td>
<td align="center">{{post.nom}}</td>
<td align="center">{{post.prenom}}</td>
<td align="center">{{post.email}}</td>
<td align="center">{{post.adresse}}</td>
<td align="center"><a ui-sref="app.modifier({customerID:post.id})">Modify</a></td>
</tr>
</tbody>
</table>
</div>
this is the "PostController" in which I get the list of clients:
.controller('PostsCtrlAjax', ['$scope','$rootScope', '$http' , '$window' ,function($scope,$rootScope,$http,$window) {
$scope.errors = [];
$scope.msgs = [];
$rootScope.usersData ;
$http({method: 'GET', url: 'http://localhost/onlinefacturation/web/app.php/apiclient/clients.json'})
.success(function(data){
$scope.errors.splice(0, $scope.errors.length); // remove all error messages
$scope.msgs.splice(0, $scope.msgs.length);
$scope.posts = data; // response data
$rootScope.usersData = angular.toJson($scope.posts);
console.dir($rootScope.usersData);
}).error(function(data, status, headers, config) {
console.log("data error ...");
});}])
When I clic on "Modify" link I am redirected to modify.html which contains the table's data values in input text:
<tabset class="tab-container">
<tab ng-controller="editController" >
<div class="row">
<div class="form-group">
<label class="col-sm-1 control-label">Nom:</label>
<div class="col-sm-1">
<input type="text" class="form-control rounded" ng-model="usernom" id="nom" value="">
</div>
</div></div> </tab></tabset>
the "editController" is responsible for sending the modified data(in case I modify) from the text inputs to the database with rest web services:
.controller('editController', ['$scope','$rootScope', '$http',function($scope,$rootScope,$http) {{
$scope.errors = [];
$scope.msgs = [];
$scope.usershow = function() {
$scope.errors.splice(0, $scope.errors.length); // remove all error messages
$scope.msgs.splice(0, $scope.msgs.length);
$scope.path = window.location.href;
$scope.userid = $scope.path.split("/").pop();
$http({method: 'GET', url: 'http://localhost/onlinefacturation/web/app_dev.php/apiclient/modifier?id='+$scope.userid+'&nom='+$scope.usernom}).success(function(data, status, headers, config){
if (data.msg != '')
{
$scope.msgs.push(data.msg);
}
else
{
$scope.errors.push(data.error);
}
}).error(function(data, status) { // called asynchronously if an error occurs
$scope.errors.push(status);
});}}])
the routing file:
.state('app.modifier', {
url: '/client/modifier/:customerID',
templateUrl: 'tpl/modify.html',
controller: 'editController'
})
the problem is that when I clic on button Modify,I didn't get values in the input text (in the modify.html page),How can I send the data from a table or that I get from a web service to an input text in another web page??thanks for help
You share data between controller via angular service instance
First, Create a angular service to retrieve and hold common table data
angular.module('app').service('TableService', function() {
var tableData = {};
this.getTableData = function() {
// use $http.get to get data from server
// save data in service local var
}
this.getTableRow = function(id) {
// return record from tableData that matches this ID
}
}
Second, inject this service in your controllers to access the data
angular.module('app').controller('editController', function(TableSerivce, $routeParams) {
var editingTableRow = TableService.getTableRow($routeParams.customerId);
// get the data that you need to update and put into the input text elements or components in your modify html via scope vars here
}
PS: This is a psuedo code to give you a brief idea of it. Watch this Egghead video for more details

Bind json to HTML table with AngularJS on page load

I have a simple proof-of-concept I'm using as a base to learn some AngularJS. The code displays some JSON data in an HTML table, as follows:
HTML:
<div ng-app="myApp">
<div ng-controller="PeopleCtrl">
<p>Click <a ng-click="loadPeople()">here</a> to load data.</p>
<table>
<tr>
<th>Id</th>
<th>First Name</th>
<th>Last Name</th>
</tr>
<tr ng-repeat="person in people">
<td>{{person.id}}</td>
<td>{{person.firstName}}</td>
<td>{{person.lastName}}</td>
</tr>
</table>
</div>
</div>
JS:
var mockDataForThisTest = "json=" + encodeURI(JSON.stringify([
{
id: 1,
firstName: "Peter",
lastName: "Jhons"},
{
id: 2,
firstName: "David",
lastName: "Bowie"}
]));
var app = angular.module('myApp', []);
function PeopleCtrl($scope, $http) {
$scope.people = [];
$scope.loadPeople = function() {
var httpRequest = $http({
method: 'POST',
url: '/echo/json/',
data: mockDataForThisTest
}).success(function(data, status) {
$scope.people = data;
});
};
}
A fiddle is here: http://jsfiddle.net/TUJ9D/
This works nicely; when you click the link, it calls 'loadPeople' and the json is pulled into the table. However, what I'd like to do is bind this when the page loads, so the user doesn't have to manually click the link to see the data in the table.
I wondered what the best way to do this is? Instinct is telling me to call the function with jquery on page load, but then I don't know if that's a good approach or whether Angular could do this in a better way itself.
Thanks folks.
Just call the load function in your controller.
function PeopleCtrl($scope, $http) {
$scope.people = [];
$scope.loadPeople = function() {
var httpRequest = $http({
method: 'POST',
url: '/echo/json/',
data: mockDataForThisTest
}).success(function(data, status) {
$scope.people = data;
});
};
$scope.loadPeople();
}
http://jsfiddle.net/TUJ9D/1/
you can simple add ng-init="loadPeople()" directive inside your <div>.
i.e.
<div ng-controller="PeopleCtrl" ng-init="loadPeople()">

why is this resource not updating the view after using $delete method

In my angular app I have a controller as follows:
function TemplateListControl($scope, TemplateService){
$scope.templates = TemplateService.get(); // Get objects from resource
// Delete Method
$scope.deleteTemplate = function(id){
$scope.templates.$delete({id: id});
}
}
Within the view I have a table thats bound to templates model. as follows:
<table ng-model="templates">
<thead>
<tr>
<th style="width:40%">Title</th>
<th style="width:40%">controls</th>
</tr>
<thead>
<tbody>
<tr ng-repeat="template in templates">
<td>
<!-- Link to template details page -->
<a href="#/template/[[template.id]]">
[[template.title]]
</a>
</td>
<td>
<!-- Link to template details page -->
<a class="btn btn-primary btn-small"
href="#/template/[[template.id]]">Edit
</a>
<!-- Link to delete this template -->
<a class="btn btn-primary btn-small"
ng-click="deleteTemplate(template.id)">Delete
</a>
</td>
</tr>
</tbody>
</table>
Now when I click on the delete link in the above template, It calls the deleteTemplate method and a successful DELETE call is made to the REST api. But the view does not get updated until it is refreshed and $scope.templates = TemplateService.get(); is initiated again. What am I doing wrong?
I prefer using promises instead of callback. Promises are the new way to handle asynchronous processes. You can inspect the result using a a promise right after it came back from the server.
//Controller
myApp.controller('MyController',
function MyController($scope, $log, myDataService) {
$scope.entities = myDataService.getAll();
$scope.removeEntity = function (entity) {
var promise = myDataService.deleteEntity(entity.id);
promise.then(
// success
function (response) {
$log.info(response);
if (response.status == true) {
$scope.entities.pop(entity);
}
},
// fail
function (response) {
$log.info(response);
// other logic goes here
}
);
};
});
//DataService
myApp.factory('myDataService', function ($log, $q, $resource) {
return {
getAll: function () {
var deferred = $q.defer();
$resource('/api/EntityController').query(
function (meetings) {
deferred.resolve(meetings);
},
function (response) {
deferred.reject(response);
});
return deferred.promise;
},
deleteEntity: function (entityId) {
var deferred = $q.defer();
$resource('/api/EntityController').delete({ id: entityId},
function (response) {
deferred.resolve(response);
},
function (response) {
deferred.reject(response);
});
return deferred.promise;
}
};
});
//Web API Controller
public class MeetingController : BaseApiController
{
// .... code omited
public OperationStatus Delete(int entityId)
{
return _repository.Delete(_repository.Single<MyEntity>(e => e.EntityID == entityId));
}
}
Note: $log, $q, $resource are built in services. Hope it helps :)
You also have to update client side so modify your source code as below
ng-click="deleteTemplate($index)">
$scope.delete = function ( idx ) {
var templateid = $scope.templates[idx];
API.Deletetemplate({ id: templateid.id }, function (success) {
$scope.templates.splice(idx, 1);
});
};
You could pass a callback function to $resource.$delete
function TemplateListControl($scope, TemplateService){
$scope.templates = TemplateService.get(); // Get objects from resource
// Delete Method
$scope.deleteTemplate = function(id){
TemplateService.$delete({id: id}, function(data) {
$scope.templates = data;
});
}
}
Attention
If your REST APIs delete function returns an array you have to set isArray: true in your Angular $resource to avoid a AngularJS $resource error - TypeError: Object # has no method 'push'
$resource(URL, {}, {
delete: {method:'DELETE', isArray: true}
});

Resources