I am new to angularjs , I have trying to create fixed Page links in dir-pagination-controls in angularjs
I have try to use 'total-items=100' but not working ,
I am getting all my values from web services ,
What I have tried
app.controller('listdata',['$scope', '$http', function($scope, $http) {
$scope.xxxx = []; //declare an empty array
data = [];
function getResultsPage(pageNumber) {
console.log('Please wait while data is loadind');
$http({
method: 'POST',
url: ajaxurl,
params: {
'action': 'get_xxxx',
'pageNumber': pageNumber,
'usersPerPage': $scope.usersPerPage
}
}).success(function (data, status, headers, config) {
$scope.xxxx = $scope.xxxx.concat(data);
$scope.totalUsers = 100;
});
}
$scope.users = [];
$scope.totalUsers = 0;
$scope.usersPerPage = usersPerPage; // this should match however many results your API puts on one page
getResultsPage(1);
$scope.pagination = {
current: 1
};
$scope.pageChanged = function(newPage) {
console.log(newPage);
getResultsPage(newPage);
};
$scope.sort = function (keyname) {
$scope.sortKey = keyname; //set the sortKey to the param passed
$scope.reverse = !$scope.reverse; //if true make it false and vice versa
};
}]);
<tr dir-paginate="xxxx in xxxxs|orderBy:sortKey:reverse|filter:search|itemsPerPage:usersPerPage" >
<!--td>{{xxxx.id}}</td-->
<td>{{xxxx.name}}</td>
<td>{{xxxx.neighborhood}}</td>
<td class="td-edit"><img src="<?php echo esc_url(get_template_directory_uri()); ?>/dist/images/edit.png"></td>
</tr>
<dir-pagination-controls on-page-change="pageChanged(newPageNumber)"></dir-pagination-controls>
Related
I have a requirement where I want to bind dropdownlist using MVC and angular JS.
I tried like below
var app1 = angular.module('Assign', [])
app1.controller('SAPExecutive_R4GState', function ($scope, $http, $window) {
// alert(UMSLocationDetails);
var LocObj = JSON.parse(UMSLocationDetails)
var ZoneValue = "";
$.each(LocObj, function (index, element) {
ZoneValue += element.LocationID + ",";
});
ZoneValue = ZoneValue.substr(0, ZoneValue.length - 1);
var Values = { "MaintZones": ZoneValue };
alert(JSON.stringify(Values));
$scope.DefaultLabel = "Loading.....";
$http({
method: "POST",
url: "/App/GetR4GStates",
dataType: 'json',
data: JSON.stringify(Values),
headers: { "Content-Type": "application/json" }
}).success(function (result) {
$scope.DefaultLabel = "--Select--";
$scope.State = data;
});
post.error(function (data, status) {
$window.alert(data.Message);
});
});
<select id="SAPExecutive_R4GState" class="form-control" ng-model="R4GState.Selected" ng-controller="SAPExecutive_R4GState as R4GState" ng-init="Select" ng-options="b for b in list">
</select>
And my CS code
[HttpPost]
public JsonResult GetR4GStates(string MaintZones)
{
List<SelectListItem> lstR4GState = new List<SelectListItem>();
try
{
Filters ObjFilter = new Filters();
DataTable dt = ObjFilter.GetR4GState(MaintZones);
if (dt.Rows.Count > 0)
{
lstR4GState = (from DataRow dr in dt.Rows
select new SelectListItem()
{
Text = Convert.ToString(dr["R4GSTATENAME"]),
Value = Convert.ToString(dr["R4GSTATECODE"])
}).ToList();
}
else
{
SelectListItem slEmptyData = new SelectListItem();
slEmptyData.Text = "No Data found";
slEmptyData.Value = "No Data found";
lstR4GState.Add(slEmptyData);
}
}
catch (Exception e)
{
}
// ErrorLog.HandleErrorLog("", "", "GetR4GStates", "Error2");
return Json(lstR4GState);
}
I am getting values in return Json(lstR4GState); but the values are not getting set in the dropdown.
Please suggest where I am going wrong as I am new to angular
It is recommended to user THEN and CATCH in AngularJS > 1.5
This should work:
angular.module('Assign', [])
.controller('SAPExecutive_R4GState', function($scope, $http, $window) {
const payload = {};
$http.get('https://dog.ceo/api/breeds/list/all', payload)
.then(function(response) {
// Please be aware RESPONSE contains the whole response.
// You probably want RESPONSE.DATA
console.log(response.data);
})
.catch(function(err) {
// do something with err message });
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="Assign" ng-controller="SAPExecutive_R4GState"></div>
Please note this example uses a GET request, just so i could show it works,
in a GET request, the payload will be added as querystring
If you change it to $http.post, the payload will be added into the body of the request.
I was trying to clean my angular app code up. So I moved all the controllers in their own files. But when I moved the controllers, my main app stoped working and started throwing the exception below -
Error: $injector:modulerr
Module Error
Then I tried searching for the why the module won't load but with no luck.
main.js /*File where app module is declared*/
var app = angular.module('app', ['ngRoute','thatisuday.dropzone','UserController','LinkController','articleController']);
I tried injecting the dependency for the controller files.
Controllers:
Link Controller
var app = angular.module('app');
app.controller('LinkController', ['$scope','$http','$sce',function ($scope, $http, $sce) {
/*Sce declaration required for proxy settings*/
$scope.renderHtml = function (html_code) {
return $sce.trustAsHtml(html_code);
};
$scope.trustSrc = function (src) {
return $sce.trustAsResourceUrl(src);
};
/*First AJAX request which gets all the links and categories for the user*/
$http({
method: 'GET',
url: '/users'
}).then(function successCallback(response) {
$scope.user = response.data;
}, function errorCallback(response) {
});
$scope.getUser = function () {
$http({
method: 'GET',
url: '/users'
}).then(function successCallback(response) {
$scope.user = response.data;
}, function errorCallback(response) {
});
};
$http({
method: 'GET',
url: '/links'
}).then(function successCallback(response) {
this.orderProp = 'age';
/*the response is saved in scope variables*/
$scope.links = response.data[0];
$scope.categories = response.data[1];
$scope.categorytolink = response.data[2];
}, function errorCallback(response) {
console.log('There was a problem! Refresh!');
});
/*AJAX request for getting the recommendations according to the most viewed stars*/
$http({
method: 'GET',
url: '/recommendations/top'
}).then(function successCallback(response) {
$scope.recommendations = response.data;
}, function errorCallback(response) {
});
/*AJAX request when a user clicks a link retrieves the link data*/
$scope.getLinkData = function (link) {
$http({
method: 'GET',
url: "/proxy",
headers: {
"X-Proxy-To": link.rss_link
}
}).then(function successCallback(response) {
/*AJAX request: add a star to the link*/
$http.post('/links/' + link.id + '/views/add', {'link': link}).then(function successCallback(data, status, headers, config) {
// Manually increment star for link just clicked
var $data;
$data = data.data;
$scope.link = $data;
console.log('200 OK! Star added');
}, function errorCallback() {
console.log('Error!');
});
/*The data will be retrieved and will be sorted according to the requirements of welcome.blade*/
$myXml = response.data;
$xmlObj = $.parseXML($myXml);
$newsItems = [];
$channelImage = $($xmlObj).find("channel>image");
/*the information of the link is sorted */
$linkData = {
"title": $channelImage.find("title").text(),
"link": $channelImage.find("link").text(),
"imgurl": $channelImage.find("url").text()
};
/*the data is sorted below*/
$.each($($xmlObj).find("item"), function (index, value) {
$newsItems.push({
"title": $(value).find("title").text(),
"description": $(value).find("description").text(),
"link": $(value).find("link").text(),
"date_published": moment($(value).find("pubDate").text()).format('MMMM Do YYYY'),
"time_published": moment($(value).find("pubDate").text()).format('h:mm:ss a'),
"guid": $(value).find("guid").text()
})
});
$scope.newsItems = $newsItems;
$scope.linkData = $linkData;
}, function errorCallback(response) {
});
};
/*Create a category private to the user*/
$scope.create_category = function (category) {
/*AJAX request: adds a new category*/
$http.post('/categories/new', {'category': category}).then(function successCallback(response) {
/*AJAX request: Updates the categories for the use of new category*/
$http({
method: 'GET',
url: '/categories'
}).then(function successCallback(response) {
$scope.categories = response.data;
}, function errorCallback(response) {
});
}, function errorCallback(response) {
});
};
}]);
User Controller
var app = angular.module('app');
app.controller("UserController", ['$scope','$http','$sce', function ($scope, $http, $sce) {
/*Sce declaration required for proxy settings*/
$scope.renderHtml = function (html_code) {
return $sce.trustAsHtml(html_code);
};
$scope.trustSrc = function (src) {
return $sce.trustAsResourceUrl(src);
};
$scope.dzOptions = {
paramName: "file",
dictDefaultMessage: "<h4><i class='fa fa-camera'></i> <b>Upload</b></h4>",
createImageThumbnails: false,
autoDiscover: false
};
$scope.dzCallbacks = {
'sending': function (file, xhr, formData) {
formData.append('_token', $('#csrf-token').val());
},
'success': function (file, response) {
$scope.user = response;
$.notify("Profile photo changed!", "success", {autoHide: true, autoHideDelay: 500});
}
};
/*Update user info*/
$scope.updateUser = function () {
/*AJAX request: update user info*/
$http.post('/users/update', {
'name': $scope.user.name,
'username': $scope.user.username,
'email': $scope.user.email
}).then(
function successCallback(data) {
$scope.user = data;
$.notify("User updated!", "success", {autoHide: true, autoHideDelay: 500});
console.log('200 OK! User updated');
}, function errorCallback() {
console.log('Error!');
});
};
}]);
Article Controller
var app = angular.module('app');
app.controller("articleController", ['$scope','$http','$sce', function ($scope, $http, $sce) {
/*Sce declaration required for proxy settings*/
$scope.renderHtml = function (html_code) {
return $sce.trustAsHtml(html_code);
};
$scope.trustSrc = function (src) {
return $sce.trustAsResourceUrl(src);
};
/*Populates the comments for particular
* */
$scope.populatecomments = function (newsItem) {
$http({
method: 'GET',
url: '/articles/' + newsItem.guid + '/comments'
}).then(function successCallback(response) {
$scope.comments = response.data;
}, function errorCallback(response) {
});
};
$scope.data = [];
$scope.comment = [];
$scope.btn_add = function (newsItem) {
if ($scope.txtcomment != '') {
$scope.data.push({
"comment": $scope.txtcomment,
"guid": newsItem.guid
});
$http.post('/comments/new', {
"comment": $scope.txtcomment,
"guid": newsItem.guid
}).then(function successCallback() {
var encodedURI = encodeURIComponent(newsItem.guid);
$http({
method: 'GET',
url: '/articles/' + encodedURI + '/comments'
}).then(function successCallback(response) {
$scope.comments = response.data;
$scope.txtcomment = "";
}, function errorCallback(response) {
});
}, function errorCallback() {
console.log('Error comment!');
});
}
};
$scope.savearticle = function (newsItem) {
$http.post('/saved-articles/save', newsItem).then(function successCallback(response) {
/*console.log(document.getElementById("save/"+newsItem.guid).className="disabled");*/
}, function errorCallback(response) {
});
}
/**
* The saved articles by the user will be retrieved when a button clicked
*/
$scope.getSavedArticles = function () {
/*AJAX request: retreive the saved the saved articles for the user*/
$http({
method: 'GET',
url: '/saved-articles'
}).then(function successCallback(response) {
$scope.linkData = null;
$scope.newsItems = response.data;
}, function errorCallback(response) {
});
};
}]);
HELP needed!
Yo do not need to declare module in each controller file. Remove the line in each controller
var app = angular.module('app');
You are injecting controller in you module like dependency.
Change your main.js file to this:
var app = angular.module('app', ['ngRoute','thatisuday.dropzone']);
#Sajeetharan is right you do not need module declaration in all controllers.
Since you are using laravel according to your comment. ( It will conflict with your blade template because both use same {{ }} for variables )
There are two ways to do this:
Change the Angular Tags
var app = angular.module('app', [], function($interpolateProvider) {
$interpolateProvider.startSymbol('<%');
$interpolateProvider.endSymbol('%>');
});
Now Laravel will use the {{ variableName }} and Angular will use <%
variableName %>.
Change the Laravel Blade Tags
Blade::setContentTags('<%', '%>');// for variables and all things Blade
Blade::setEscapedContentTags('<%%', '%%>');// for escaped data
Variables will be: <% $variable %>. Comments will be: <%-- $variable
--%>. Escaped data will look like: <%% $variable %%>.
You can check this Tutorial for more info.
Hi I am developing web application in angularjs. I have requirement below. I have one factory. I have added code snippet below.
myapp.factory('sadadpaymentapi', ['$http', '$cookieStore', 'cfg', 'ScrollFunction', 'leaselisting', function ($http, $cookieStore, cfg, ScrollFunction, leaselisting) {
var sadadpaymentapiobject = {};
var baseurl = cfg.Baseurl;
var LoginID = $cookieStore.get("LoginID");
var cookiePreferredLanguage = $cookieStore.get('PreferredLanguage');
var urlapi = baseurl + "api/ServiceRequest/CreateRSSedad/";
sadadpaymentapiobject.callsadad = function (PaymentType) {
leaselisting.leaselisting().then(function (response) {
//Problem in calling
}, function (error) { });
var request = {
url: urlapi,
method: 'POST',
data: {
SRActivityID: LoginID,
PaymentType: PaymentType,
PaymentAmount: "100"
},
headers: ScrollFunction.getheaders()
};
return $http(request);
}
return sadadpaymentapiobject;
}]);
Here is my second factory leaselisting
myapp.factory('leaselisting', ['$http', '$cookieStore', 'cfg', 'ScrollFunction', function ($http, $cookieStore, cfg, ScrollFunction) {
var leaselistingobject = {};
var baseurl = cfg.Baseurl;
var LoginID = $cookieStore.get("LoginID");
var cookiePreferredLanguage = $cookieStore.get('PreferredLanguage');
leaselistingobject.leaselisting=function(){
var requestObj = {
url: "api/ServiceRequest/GetROLSPSRLeaseList/",
data: {
LoginID: LoginID,
RSAccountNumber: $cookieStore.get("AccountNumber")
},
headers: ScrollFunction.getheaders()
};
$http(requestObj).then(function (response) {
}, function (error) {
});
}
return leaselistingobject;
}]);
I have found error in below line
leaselisting.leaselisting().then(function (response) { //Problem in calling
}, function (error) { });
May i am i doing anything wrong in the above code? May i know is it possible to call one factory from another? The response i get from leaselisting i want to pass it in callsadad function of sadadpaymentapi. So can someone hep me in the above code? I am getting error Cannot read property 'then' of undefined in the leaselisting.leaselisting().then(function (response) {},function(error){});
Also is there any way I can directly inject factory like payment amount: inject factory something like this?
I assume, that leaselistingobject.getValue is an asynchronous function.
So first of get your value :
leaselistingobject.getValue = function(){
var requestObj = {
url: "api/ServiceRequest/getValue/"
};
return $http(requestObj).then(function (response) {
return response.data;
});
}
And then use it. To let all async actions finish we use angulars $q.Here you can find a small tutorial.
myapp.factory('sadadpaymentapi', ['$http', '$cookieStore', 'cfg', 'ScrollFunction', 'leaselisting', '$q',function ($http, $cookieStore, cfg, ScrollFunction, leaselisting, $q) {
var sadadpaymentapiobject = {};
var baseurl = cfg.Baseurl;
var LoginID = $cookieStore.get("LoginID");
var cookiePreferredLanguage = $cookieStore.get('PreferredLanguage');
var urlapi = baseurl + "api/ServiceRequest/CreateRSSedad/";
sadadpaymentapiobject.callsadad = function (PaymentType) {
var leastListingPromise = leaselisting.leaselisting();
var getValuePromise = leaselisting.getValue();
$q.all([leastListingPromise, getValuePromise]).then(function (responses) {
//Here you have both responses in an array
var request = {
url: urlapi,
method: 'POST',
data: {
SRActivityID: LoginID,
PaymentType: PaymentType,
PaymentAmount: responses[1]
},
headers: ScrollFunction.getheaders()
};
return $http(request);
});
}
return sadadpaymentapiobject;
}]);
To make leaselisting() return the response of the request change the end of the function from
$http(requestObj).then(function (response) {
}, function (error) {
});
to
return $http(requestObj).then(function (response) {
return response.data;
}, function (error) {
});
If wont do anything about possible errors you can omit the error function part:
return $http(requestObj).then(function (response) {
return response.data;
});
This is my factory service and it is fetching data from a web service
var customersFactory = function ($http) {
var customer = [];
var getCustomersURL = "http://localhost:50340/Services/CustomerService.asmx/GetCustomers";
customer.XMLtoJSON = function (data) {
data = data.replace('<?xml version="1.0" encoding="utf-8"?>', ''); ;
data = data.replace('<string xmlns="http://tempuri.org/">', '').replace('</string>', '');
return $.parseJSON(data);
};
customer.GetCustomers = function () {
$http.post(getCustomersURL).success(function (data, status, headers, config) {
return customer.XMLtoJSON(data);
}).error(function (ata, status, headers, config) { });
};
return customer;
};
app.factory('customersFactory', customersFactory);
Now, this is being used in my controller
app.controller("CustomersController", function ($scope, customersFactory) {
var service = [];
service = customersFactory.GetCustomers();
$scope.Customers = service;
if ((typeof (service) != 'undefined') && service.length > 0) {
service.then(function (result) {
$scope.Customers = result;
});
}
});
The value of service is always undefined or empty. Data is not being passed from factory to controller. Im calling a simple web service, no fancy APIs or WCF.
It there was some static/dummy data, its working fine. The controller is fetching the data and is being displayed.
Where am I doing wrong?
Any help is greatly appreciated.
Thank you
change this line var customer = []; to this var customer = {};
Or better yet make it a class...
change this to return the promise:
customer.GetCustomers = function () {
return $http.post(getCustomersURL).error(function (data, status, headers, config) { });
};
and usage in the controller:
app.controller("CustomersController", function($scope, customersFactory) {
$scope.Customers = [];
customersFactory.getCustomers().success(function(data, status, headers, config) {
$scope.Customers = customersFactory.XMLtoJSON(data);
});
});
I have an array that I want to affect to it data that I have get from my Factory,but when I try to access it I don't get the data recently added to it,this the array when I try to fill it whith data:
$scope.copyofOpList = [];
$scope.UpdateOperations = function() {
$scope.copyofOpList = gammeOfFactory.getListOperations();
}
this is my Factory from which I get the Data:
.factory(
'gammeOfFactory',
function($http, $q) {
var backObject = {
getListOperations: _getListOperations
}
return backObject;
//used to get list of operations from ws
function _getListOperations() {
var defer = $q.defer();
$http({
method: "GET",
url: "MyWebService/getAll"
}).then(function mySucces(response) {
defer.resolve(response.data);
}, function myError(response) {
deferred.reject('Erreur into url ' + response);
});
return defer.promise;
};
});
so please,how can I refresh the Data in this array without refreshing the web page
thanks for help