how to automatically update data on the view in angular.js - javascript

i have show the phone data on the view site :
<table class="table table-stripes data-tables" ng-controller="GetData as mydata">
<tr>
<th align="center"><div align="center">S.#</div></th>
<th align="center"><div align="center">Name</div></th>
<th align="center"><div align="center">Number</div></th>
<th align="center"><div align="center">Edit</div></th>
<th align="center"><div align="center">Delete</div></th>
</tr>
<tr ng-repeat="alldata in mydata.row | filter:search ">
<td>{{alldata.id}}</td>
<td>{{alldata.name}}</td>
<td>{{alldata.numbers}}</td>
<td><button class="btn btn-primary">Edit</button></td>
<td><button class="btn btn-danger">Delete</button></td>
</tr>
</table>
and when user add new one i want to refresh the controller. how can i do this
//getdata controller
myApp.controller("GetData",['$http','$log','$location','$timeout', function($http,$log,$location,$timeout){
var ata = this;
ata.row = [ ] ;
$http({method: 'POST', url: 'process/getdata.php'})
.success(function(data) {
// this callback will be called asynchronously
// when the response is available
// $log.log(data);
ata.row=data;
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
}]);
// add new item controller
myApp.controller("addNumber",['$http','$log','transformRequestAsFormPost','$location', function($http,$log,transformRequestAsFormPost,$location){
this.add = function(name,number){
var mydata='name='+name+'&number'+number;
$http({
method: 'POST',
url: 'process/addnumbers.php',
data:{
name: name,
number: number
}}).
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
$log.log(data);
if(data == 'true')
{
}
else
{
}
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
}
}]);
what should i do with getdata controller
what should i do when user add new record

try to refresh the page in add number controller. that might be help.
myApp.controller("addNumber",['$http','$log','transformRequestAsFormPost','$location','$route', function($http,$log,transformRequestAsFormPost,$location,$route){
this.add = function(name,number){
var mydata='name='+name+'&number'+number;
$http({
method: 'POST',
url: 'process/addnumbers.php',
data:{
name: name,
number: number
}}).
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
$log.log(data);
if(data == 'true')
{
$route.reload();
// get the current path
$location.path();
// change the path
$location.path('/Dashboard');
}
else
{
}
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
}
}]);
inject $route service in the controller

Related

Issue with populating partial view with AngularJs and MVC

I am new to AngularJs. I am using a partial view for Create and Edit operation but facing some issue wile retrieving the data.
The data is being retrieved successfully from my MVC controller but is unable to populate the view.
Here is the JS I am using
(function (angular) {
'use strict';
angular.module('Sub_Ledger_Category_Create_app', [])
.controller('Sub_Ledger_Category_Create_ctrl', function ($scope, $http, $location) {
$scope.SubLedgerCategoryModel = {};
GetRequestType();
function GetRequestType() {
$http.get('/Common/Get_Action_Request')
.success(function (result) {
//debugger;
// $scope.SubLedgerCategoryModel = data;
if (result == "Create") {
$("#txt_Master_Subledger_Category").html("<h3 class='box-title'> Create Sub Ledger Category </h3>");
// $("#txt_Master_Accounting_Group_Group_id").val(0);
}
else {
$("#txt_Master_Subledger_Category").html("<h3 class='box-title'> Edit Sub Ledger Category</h3>");
//GetEditData();
$scope.GetEditData();
}
$("#Master_Subledger_Category").val(result)
NProgress.done();
})
.error(function (data, status, headers, config) {
NProgress.done();
$("div.failure").text("Unable to retrieve Request Type");
$("div.failure").fadeIn(300).delay(1500).fadeOut(400);
});
};
$scope.GetEditData = function () {
$http.get('/Master_Subledger_Category/GetEditData')
.success(function (data, status, headers, config) {
debugger;
$scope.SubLedgerCategoryModel = data;
console.log(data);
})
.error(function (data, status, headers, config) {
NProgress.done();
$("div.failure").text("Retrive Failure");
$("div.failure").fadeIn(300).delay(1500).fadeOut(400);
});
};
$scope.InsertSubledgerCategory = function () {
NProgress.start();
var Request_Type = $("#Master_Subledger_Category").val();
var Url_Master_Subledger;
if (Request_Type == "Create") {
Url_Master_Subledger = "/Master_Subledger_Category/Create_Master_Subledger_Category_Ajax";
}
else {
Url_Master_Subledger = "/Master_Subledger_Category/Test";
}
$http({
method: 'POST',
url: Url_Master_Subledger,
data: $scope.SubLedgerCategoryModel
}).success(function (data, status, headers, config) {
if (data.success === true) {
NProgress.done();
$("div.success").text("Successfully Created");
$("div.success").fadeIn(300).delay(1500).fadeOut(800);
$scope.SubLedgerCategoryModel = {};
console.log(data);
}
else {
NProgress.done();
$("div.failure").text("Saveing Failure");
$("div.failure").fadeIn(300).delay(1500).fadeOut(400);
}
}).error(function (data, status, headers, config) {
NProgress.done();
$("div.failure").text("Saveing Failure");
$("div.failure").fadeIn(300).delay(1500).fadeOut(400);
console.log($scope.message);
});
};
})
.config(function ($locationProvider, $sceProvider) {
$locationProvider.html5Mode({
enabled: true,
requireBase: false
});
$sceProvider.enabled(false);
});
})(angular);
Here is the HTML:
<div class="form-horizontal" ng-app="Sub_Ledger_Category_Create_app">
<div class="box-body" ng-controller="Sub_Ledger_Category_Create_ctrl">
<div class="form-group">
<label for="txt_Master_Subledger_Category_Name" class="col-sm-2 control-label">Sub Ledger Category</label>
<div class="col-sm-10">
<input class="form-control" ng-model="SubLedgerCategoryModel.Sub_Ledger_Cat_Name" id="txt_Master_Subledger_Category_Name" name="txt_Master_Subledger_Category_Name" autofocus placeholder="Sub Ledger Category">
<input ng-model="SubLedgerCategoryModel.Sub_Ledger_Cat_ID" name="txt_Master_Subledger_Category_ID" id="txt_Master_Subledger_Category_ID" hidden />
</div>
</div>
<!-- /.box-body -->
<div class="box-footer">
<button type="submit" value="Save" ng-click="InsertSubledgerCategory()" class="btn btn-info pull-right">Save</button>
<div class="text-red alert-box failure pull-right margin-r-5"></div>
<div class="text-green alert-box success pull-right margin-r-5"></div>
</div>
<!-- /.box-footer -->
</div>
</div>
Unfortunately I am unable to populate the view but in Console log I am able to view the data, helpful if anybody and help me.
AngularJs prevents loading HTML in this way by default. You might be getting an error on browser console: attempting to use an unsafe value in a safe context.
This is due to Angular's Strict Contextual Escaping (SCE) mode (enabled by default). Have a look to this for more information.
To resolve this issue you have 2 solutions:
$sce
$scope.thisCanBeusedInsideNgBindHtml = $sce.trustAsHtml(someHtmlVar);
ngSanitize: include the angular-sanitize.min.js resource and add the dependency in module.
hope this will help.
I have only changed the following
scope.SubLedgerCategoryModel = data;
to
scope.SubLedgerCategoryModel = data[0]:
and its resolved my issue.

Loader not being shown on ajax request in angular js

Since I am using ajax request using $http. It takes a long time since my operation on server takes time. I need to show loader while processing request, but the loader does not show. Although my code seems correct. I tried different methods but did not work.
Index.html
<body ng-app="app">
<!-- loader, can be used on multiple pages-->
<div class="loading loader-quart" ng-show="isLoading"></div>
<!-- my logic -->
</body>
addCtrl.js
//method to get all the attributes and send to server using service
$scope.add = function () {
if ($scope.Option == 'newInstance')
$scope.singleObject.FK_Name = 'MetisEmptyTemplate';
$rootScope.isLoading = true;
var featuresList = websiteService.getUpdatedTree($scope.treeDataSource);
var formData = new Website("", $scope.singleObject.Name, $scope.singleObject.DisplayName, $scope.singleObject.Description, $scope.singleObject.State, "", $scope.singleObject.FK_Name, $scope.singleObject.Email, featuresList);
websiteService.addwebsite(formData);
$rootScope.isLoading = false;
}
websiteService.js
//service to add website
this.addwebsite = function (website) {
$http({
method: 'POST',
url: $rootScope.url + 'Add',
data: JSON.stringify(website),
contentType: 'application/json'
}).success(function (data) {
alert(data);
}).error(function (data, status, headers, config) {
//alert(data);
});
}
Since I am going to turn isLoading as "true" in start and then after request completes I turn isLoading "false". Where is the problem in code?
Your websiteServices code gets executed asynchronously. Which means that the above code would display the loader and then pretty much hide it again instantly.
To handle async code in the controller you must return a promise from the service and put the hiding of the spinner in a callback function using .then().
service:
this.addwebsite = function (website) {
var deferred = $q.defer();
$http({
method: 'POST',
url: $rootScope.url + 'Add',
data: JSON.stringify(website),
contentType: 'application/json'
}).success(function (data) {
alert(data);
deferred.resolve(data);
}).error(function (data, status, headers, config) {
//alert(data);
deferred.reject(data);
});
return deferred.promise
}
controller:
websiteService.addwebsite(formData).then(function(){
$rootScope.isLoading = false
});
this.insertMliveResponse = function(data){
var defer=$q.defer();
var requestURL='/mlive-portlet/rest/mliveResponseService/insertmLiveResponse';
httpRequest(requestURL,data).then(function(data){
defer.resolve(data.data);
},function(data){
defer.reject(data.data);
})
return defer.promise;
}
If you are making request then,
I think the best way to show hide loader is interceptor
In my snippet, I am using loader service to activate/deactivate loader
For Eg:
// http.config.js file
export function httpConfig($httpProvider, AuthInterceptProvider) {
'ngInject';
AuthInterceptProvider.interceptAuth(true);
// added for show loader
$httpProvider.interceptors.push(function (loaderService, $q) {
'ngInject';
return {
'request': function (config) {
loaderService.switchLoaderModeOn();
return config;
},
'requestError': function (rejection) {
loaderService.switchLoaderModeOff();
return $q.reject(rejection);
},
'response': function (response) {
loaderService.switchLoaderModeOff();
return response;
},
'responseError': function (rejection) {
loaderService.switchLoaderModeOff();
return $q.reject(rejection);
}
};
});
}
// and in your module.js file
import {httpConfig} from './config/http.config';
.config(httpConfig)

get data from json array to Table angularJS

I have this json data:
{
status: "SUCCESS",
data: [
{
FirstName: "Student ",
LastName: "1",
Id: 1,
ObjectState: 0
},
{
FirstName: "Student ",
LastName: "2",
Id: 2,
ObjectState: 0
}
}
]
}
I have tried like this,in my controller and in the view:
app.js:
.controller("etudCtrl",["$scope", "$http", function ($scope, $http) {
var i;
$http({method: 'GET', url: 'MyURL'})
.success(function (data) {
for(i=0;i<data.length;i++){
$scope.paged = data[i].data; // response data
console.log($scope.paged+" $scope.paged");
}
$scope.currentPageStores= $scope.paged;
console.log($scope.currentPageStores+" values");
console.log("success");
}).error(function (data, status, headers, config) {
console.log("data error ...");
});
}])
Students.html:
<table>
<thead>...</thead>
<tbody data-ng-controller="etudCtrl">
<tr ng-repeat="store in currentPageStores" >
<td align="center">{{store.LastName}}</td>
<td align="center">{{store.FirstName}}</td>
</tr>
</tbody>
</table>
and this what I get in console:
values
success
I didn't get any data in console or in the Table :(
any help please
thanks
Update:
I try with this:
$rootScope.usersData = angular.toJson(data.data);
console.log($rootScope.usersData+" my data");
I get all the data that I want to display in console
Update2:
$http({method: 'GET', url: 'MyURL'})
.success(function (data) {
console.log(JSON.stringify(data)+"myData");
for(i=0;i<data.length;i++){
$scope.paged = data.data[i]; // response data
console.log($scope.paged+" $scope.paged");
}
.....
}
I get this in console:
{"status":"SUCCESS","data":[{"FirstName":"Student ","LastName":"1","Id":1,"ObjectState":0},{"FirstName":"Student ","LastName":"2","Id":2,"ObjectState":0}]}myData
No need to loop around in controller. Try the following:
Your Controller:
.controller("etudCtrl",["$scope", "$http", function ($scope, $http) {
$http({method: 'GET', url: 'MyURL'})
.success(function (data) {
$scope.currentPageStores= data.data;
console.log($scope.currentPageStores+ " values");
console.log("success");
}).error(function (data, status, headers, config) {
console.log("data error ...");
});
}])
Your student.html
<table>
<thead>...</thead>
<tbody data-ng-controller="etudCtrl">
<tr ng-repeat="store in currentPageStores track by $index" >
<td align="center">{{store.LastName}}</td>
<td align="center">{{store.FirstName}}</td>
</tbody>
</table>
Here is a PLUNKER example of how you access when the data comes in an array as yours : http://plnkr.co/edit/Q9ewbH7XevsOQG0Yzv6B?p=preview
You can't print a object on console with another string.
use
console.log(JSON.stringify($scope.currentPageStores)+" values");
or
console.log($scope.currentPageStores);

AngularJS $http get doesn't work but $.ajax does

I am new to AngularJS. I cannot seem to get $http to work. I have the following factory:
app.factory('employeeFactory', function ($http) {
var factory = {};
// get data form controller
var employees = [];
var Url = "../../../Employee/GetEmployees";
// this does not work ----------------------------
$http.get(Url, { params: { term: 'Step' }}).
success(function (response, status, headers, config) {
employees = response.data
}).
error(function (response, status, headers, config) {
alert(error);
});
// this works using JQuery ajax ----------------------------
$.ajax({
url: Url,
data: { term: 'Step' },
dataType: "json",
type: "GET",
error: function (request, status, error) {
alert(error);
},
success: function (response) {
$.each(response.data, function (i, obj) {
employees.push({ EmployeeName: obj.EmployeeName, EmployeeNumber: obj.EmployeeNumber });
});
}
});
factory.getEmployees = function () {
return employees
};
return factory;
});
And the following controller:
app.controller('EmployeeController', function ($scope, employeeFactory) {
$scope.employees = [];
init();
function init() {
$scope.employees = employeeFactory.getEmployees();
}
});
The ajax call in the factory works but the $https doesn't (both are in the factory, I just comment out one or the other while testing). I looked in google chrome dev tools and both calls return data in the same format, but the $http data is not being bound to the html:
<div class="container">
<h4>This is view 1</h4>
Type a name to filter: <input type="text" data-ng-model="employeeSearch" />
<ul>
<li data-ng-repeat="employee in employees | filter:employeeSearch | orderBy:'EmployeeName'">{{ employee.EmployeeName }} - {{ employee.EmployeeNumber }}</li>
</ul>
</div>
Here is the format the factory returns for both calls:
{data: [{EmployeeNumber:123456, EmployeeName:Johnson,Bob},…]
data: [{EmployeeNumber:123456, EmployeeName:Johnson,Bob},…]
0: {EmployeeNumber:123456, EmployeeName:Johnson,Bob}
EmployeeName: "Johnson,Bob"
EmployeeNumber: "123456"
I don't understand why, when both calls return the data to the view in the same format, the binding is not occurring with the $http method. Any help is appreciated
The jQuery ajax works because you push to the returned reference.
In the angular ajax success handler you overwrite the variable, but the return value is still the empty reference.
So to get the angular $http function working, you should do the following in your success handler:
angular.forEach(response.data, function(value) {
employees.push(value);
});
use this code:
service:
app.factory('employeeFactory', function ($http) {
var employees = [];
var Url = "../../../Employee/GetEmployees";
var factory = {
getEmp:function(){
return $http.get(Url, { params: { term: 'Step' }})
}
}
return factory;
});
controller:
app.controller('EmployeeController', function ($scope, employeeFactory) {
$scope.employees = [];
function init() {
employeeFactory.getEmp().then(function(data){
$scope.employees=data;
})
.catch(function(err){
console.log(err);
})
}
init();
});

Sending JSON using $http cause angular to send text/plain content type

I just want to send the following JSONobjects to my API backend:
{
"username":"alex",
"password":"password"
}
So I wrote the following function, using Angular $http:
$http(
{
method: 'POST',
url: '/api/user/auth/',
data: '{"username":"alex", "password":"alex"}',
})
.success(function(data, status, headers, config) {
// Do Stuff
})
.error(function(data, status, headers, config) {
// Do Stuff
});
I read in documentation for POST method that Content-Type header will be automatically set to "application/json".
But I realized that the content-type I receive on my backend (Django+Tastypie) api is "text/plain".
This cause my API to not respond properly to this request. How should I manage this content-type?
The solution I've moved forward with is to always initialize models on the $scope to an empty block {} on each controller. This guarantees that if no data is bound to that model then you will still have an empty block to pass to your $http.put or $http.post method.
myapp.controller("AccountController", function($scope) {
$scope.user = {}; // Guarantee $scope.user will be defined if nothing is bound to it
$scope.saveAccount = function() {
users.current.put($scope.user, function(response) {
$scope.success.push("Update successful!");
}, function(response) {
$scope.errors.push("An error occurred when saving!");
});
};
}
myapp.factory("users", function($http) {
return {
current: {
put: function(data, success, error) {
return $http.put("/users/current", data).then(function(response) {
success(response);
}, function(response) {
error(response);
});
}
}
};
});
Another alternative is to use the binary || operator on data when calling $http.put or $http.post to make sure a defined argument is supplied:
$http.put("/users/current", data || {}).then(/* ... */);
Try this;
$http.defaults.headers.post["Content-Type"] = "application/json";
$http.post('/api/user/auth/', data).success(function(data, status, headers, config) {
// Do Stuff
})
.error(function(data, status, headers, config) {
// Do Stuff
});

Categories

Resources