How to include custom filter in the code?
This is my service file. I need to filter by name. Also I need to give validations in html for save and cancel using pristine
app.factory('CrusdService', function($http) {
return {
fetchAll: function() {
return $http.get('https:\\localHost:5000\countries').then(
function(response) {
return response.data.data; // depends on the response data.Sometimes it will be response.data.data.data
},
function(error) {
return error;
}
);
},
add: function(data) {
return $http.post('https:\\localHost:5000\country', data).then(
function(response) {
return response;
},
function(error) {
console.log('error');
}
);
},
update: function(data) {
var name = {
"name": data.name
};
return $http.put('https:\\localHost:5000\country' + data._id, name).then(
function(response) {
return response;
},
function(error) {
console.log('error');
}
);
},
activate: function(id) {
return $http.put('https:\\localHost:5000\country' + id + '\activate').then(
function(response) {
return response;
},
function(error) {
console.log('error');
}
);
},
deactivate: function(id) {
return $http.put('https:\\localHost:5000\country' + id + '\deactivate').then(
function(response) {
return response;
},
function(error) {
console.log('error');
}
);
}
}
});
in html file add the following content:
For the search field give the ng-model="searchValue"
In ng-repeat = "data in country |.. | filter:searchValue"
app.filter("customSearch",function(){
return function(data,search){
var filtered = [];
if(!!search){
for(var i=0;i<data.length;i++){
if(data[i].country.toLowerCase().indexOf(search) !== -1){
filtered.push(data[i]);
}
}
}
else{
filtered = data;
}
return filtered
}
})
In html file add the following content:
For the search field give the ng-model="searchValue"
In ng-repeat = "data in country |.. | filter:searchValue"
app.filter("customSearch",function(){
return function(data,search){
var filtered = [];
if(!!search){
for(var i=0;i<data.length;i++){
if(data[i].country.toLowerCase().indexOf(search) !== -1){
filtered.push(data[i]);
}
}
}
else{
filtered = data;
}
return filtered
}
})
in html file add the following content:
<span class="error" ng-if="formname.inputname.$invalid">enter correct data</span> //add this below the save button
for disbaling save and update button in pop up
save - ng-disabled="formname.inputname.$invalid || formname.inputname.$pristine" //formname is the name of the form and inputname is name of the button. if button name is not there add one.
update - ng-disabled="formname.inputname.$invalid || formname.inputname.$pristine"
-----
ng-model="searchString" ng-change="search(searchString)">
$scope.search = function(searchValue) {
$scope.list = ($filter("filter")($scope.searchList, {name: searchValue}));
};
HTML
<div class="form-group" ng-class="{'has-error': dataForm.country.$invalid && dataForm.country.$dirty}">
<input type="text" ng-model="country" name="country" class="form-control" required>
<span class="error text-danger" ng-show="dataForm.country.$invalid && dataForm.country.$dirty">Required</span>
<input type="submit" value="Submit" ng-disabled="dataForm.$invalid">
</div>
Related
What is the use of invalid, pristine, etc in angularjs page.
How to use these for form validation?
Requirement 1:
In service file
app.factory('CrusdService', function($http) {
return {
fetchAll: function() {
return $http.get('https:\\localHost:5000\countries').then(
function(response) {
return response.data.data;
},
function(error) {
return error;
}
);
},
add: function(data) {
return $http.post('https:\\localHost:5000\country', data).then(
function(response) {
return response;
},
function(error) {
console.log('error');
}
);
},
update: function(data) {
var name = {
"name": data.name
};
return $http.put('https:\\localHost:5000\country' + data._id, name).then(
function(response) {
return response;
},
function(error) {
console.log('error');
}
);
},
activate: function(id) {
return $http.put('https:\\localHost:5000\country' + id + '\activate').then(
function(response) {
return response;
},
function(error) {
console.log('error');
}
);
},
deactivate: function(id) {
return $http.put('https:\\localHost:5000\country' + id + '\deactivate').then(
function(response) {
return response;
},
function(error) {
console.log('error');
}
);
}
}
});
In controller file
function countryList() {
CrudeService.fecthAll().then(
function(data) {
$scope.countries = data;
},
function(data) {
console.log('error');
}
);
}
countryList();
// insert within the method given for add country
CrudeService.add($scope.country).then(
function(data) {
countryList();
},
function(data) {
console.log('error');
}
);
// insert within the method given for update country
CrudeService.update($scope.country).then(
function(data) {
countryList();
},
function(data) {
console.log('error');
}
);
// insert within the method given for activate country
CrudeService.activate(itemsId).then(
function(data) {
countryList();
},
function(data) {
console.log('error');
}
);
// insert within the method given for deactivate country
CrudeService.deactivate(itemsId).then(
function(data) {
countryList();
},
function(data) {
console.log('error');
}
);
Requirement 2:
filter table data using search box
in html file add the following content:
For the search field give the ng-model="searchValue"
In ng-repeat = "data in country |.. | filter:searchValue"
Requirement 3:
validation and error message
in html file add the following content:
<span class="error" ng-if="formname.inputname.$invalid">enter correct data</span>
for disbaling save and update button in pop up
save - ng-disabled="formname.inputname.$invalid || formname.inputname.$pristine"
update - ng-disabled="formname.inputname.$invalid || formname.inputname.$pristine"
HTML
<div ng-controller="Part2ctrl">
<form novalidate name="f1" ng-submit="SaveData()">
<input type="text" name="tname" ng-model="tab1.Name" ng-class="Submitted?'ng-dirty':''" required autofocus />
<br/> CountryName <select ng-model="CountryID" ng-options="I.CountryID as I.CountryName for I in CountryList" ng-change="GetStatesd()"></select> StateName
<select ng-model="StateID" ng-options="I.StateID as I.StateName for I in StateList"></select><input type="submit" value="{{SubmitText}}" />
</form>
</div>
Javascript
angular.module("MyApp").controller("Part2ctrl", function($scope, Revservedata) {
$scope.$watch('f1.$valid', function(dee) {
$scope.isFormValid = dee;
}) $scope.SaveData = function(data) {
if ($scope.SubmitText == "Save") {
$scope.meassage = '';
$scope.isFormValid = true;
if ($scope.isFormValid) {
$scope.SubmitText = "please wait....";
Revservedata.SaveFormData($scope.tab1).then(function(d) {
alert(d);
if (d == "Sucess") {
cleardata();
}
}) Revservedata.GetCountry().then(function(d) {
$scope.CountryList = d.data;
}) $scope.GetStatesd = function(CountryID) {
Revservedata.GetStates($scope.CountryID).then(function(d) {
$scope.StateList = d.data;
})
}
}
});
}).factory("Revservedata", function($http, $q) {
var fac = {};
fac.GetCountry = function() {
return $http.get("/Home/GetCountry");
}
fac.GetStates = function(CountryID) {
return $http.get("/Home/GetStates?CountryID=" + CountryID)
}
fac.SaveFormData = function(data) {
var defer = $q.defer();
$http({
url: "/Home/Create",
method: "POST",
data: JSON.stringify(data),
header: {
'content-type': 'application/json'
}
}) return defer.promise;
}
return fac;
})
I have a list of items from the file browser of my device, I need to show different icons for different file types - pdf file, doc file, jpg file etc. For now I can show if it is a folder or if it is a file, and the arrow to go in the parent folder.
Any idea? Here is my code:
<div class="list">
<div ng-repeat="file in files">
<a class="item item-icon-left" href="#" ng-click="getContents(file.nativeURL);">
<!--<a class="item item-icon-left" href="#" ng-click="getContents(file.nativeURL);" my-on-hold="onItemHold(item)">-->
<i class="icon" ng-class="{'icon ion-folder' : file.isDirectory, 'icon ion-document' : file.isFile, 'ion-reply' : (file.name === '[BACK]')}"></i>
<!-- <i class="icon" ng-class="{'icon ion-folder' : file.isDirectory, 'icon ion-document' : file.isFile, 'ion-reply' : (file.name === '[BACK]'), 'ion-compose' : (file.isFile && file.name.split('.').pop() === 'gif')}"></i>-->
<!-- <i ng-show="file.isDirectory" class="icon ion-folder"></i>
<i ng-show="file.isFile" class="icon ion-document"></i>-->
{{file.name}}
<p>Location : {{file.nativeURL}}</p>
</a>
</div>
</div>
and js:
app.controller("ExampleController", function($scope, $cordovaFile, $ionicPlatform, $fileFactory, $cordovaPrinter, $cordovaFileOpener2, $interval) {
var fs = new $fileFactory();
$ionicPlatform.ready(function() {
fs.getEntriesAtRoot().then(function(result) {
console.log("result "+ JSON.stringify(result));
$scope.files = result;
}, function(error) {
console.error(error);
});
$scope.getContents = function(path) {
fs.getEntries(path).then(function(result) {
console.log("result "+JSON.stringify(result));
// console.log("result "+result);
//sono i files nella cartella
$scope.files = result;
var nomeFile=[];
var nomeExt=[];
for(var i = 0; i<$scope.files.length; i++){
nomeFile = $scope.files[i].name;
console.log("nomeFile "+nomeFile);
nomeExt = $scope.files[i].name.split('.').pop();
console.log("nome estenzione "+nomeExt);
};
//cartella padre
$scope.files.unshift({name: "[BACK]"});
//funzione per trovare il padre del path corrente
fs.getParentDirectory(path).then(function(result) {
// console.log("result "+result);
console.log("result "+JSON.stringify(result));
result.name = "[BACK]";
$scope.files[0] = result;
});
}, function(error){
console.error(error);
});
}
});
});
app.factory("$fileFactory", function($q, $cordovaFileOpener2,$ionicGesture,$rootScope) {
var File = function() {};
File.prototype = {
getParentDirectory: function(path) {
//questa è la promise
var deferred = $q.defer();
//accedo al file local e prendo il path
window.resolveLocalFileSystemURL(path, function(fileSystem) {
fileSystem.getParent(function(result) {
console.log("result "+JSON.stringify(result));
deferred.resolve(result);
}, function(error) {
deferred.reject(error);
});
}, function(error) {
deferred.reject(error);
});
return deferred.promise;
},
//per trovare tutti i file e cartelle nella root del device
getEntriesAtRoot: function() {
var deferred = $q.defer();
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem) {
console.log(fileSystem.name);
var directoryReader = fileSystem.root.createReader();
directoryReader.readEntries(function(entries) {
// console.log("entries "+entries);
console.log("result "+ JSON.stringify(entries));
deferred.resolve(entries);
}, function(error) {
deferred.reject(error);
});
}, function(error) {
deferred.reject(error);
});
return deferred.promise;
},
//per trovare tutti i files e cartelle nel path dato
getEntries: function(path) {
var deferred = $q.defer();
window.resolveLocalFileSystemURL(path, function(fileSystem) {
console.log(fileSystem);
console.log(fileSystem.name);
console.log(fileSystem.nativeURL);
var fileName, fileExtension;
fileName = fileSystem.name;
fileExtension = fileSystem.name.split('.').pop();
console.log (fileExtension);
var pathCompleto = fileSystem.nativeURL;
$rootScope.filePrint = pathCompleto;
console.log ("pathCompleto "+ pathCompleto);
console.log("fileSystem.isFile "+fileSystem.isFile);
if(fileSystem.isFile){
if (fileExtension === "pdf") {
$cordovaFileOpener2.open(
pathCompleto,
'application/pdf'
).then(function() {
console.log('Success');
}, function(err) {
console.log('An error occurred: ' + JSON.stringify(err));
});
}if(fileExtension === "doc") {
$cordovaFileOpener2.open(
pathCompleto,
'application/msword'
).then(function() {
console.log('Success');
}, function(err) {
console.log('An error occurred: ' + JSON.stringify(err));
});
}if(fileExtension === "txt") {
$cordovaFileOpener2.open(
pathCompleto,
'text/plain'
).then(function() {
console.log('Success');
}, function(err) {
console.log('An error occurred: ' + JSON.stringify(err));
});
}if(fileExtension === "jpeg") {
$cordovaFileOpener2.open(
pathCompleto,
'image/jpeg'
).then(function() {
console.log('Success');
}, function(err) {
console.log('An error occurred: ' + JSON.stringify(err));
});
}if(fileExtension === "jpg") {
$cordovaFileOpener2.open(
pathCompleto,
'image/jpeg'
).then(function() {
console.log('Success');
}, function(err) {
console.log('An error occurred: ' + JSON.stringify(err));
});
}if(fileExtension === "png") {
$cordovaFileOpener2.open(
pathCompleto,
'image/png'
).then(function() {
console.log('Success');
}, function(err) {
console.log('An error occurred: ' + JSON.stringify(err));
});
}if(fileExtension === "rtf") {
$cordovaFileOpener2.open(
pathCompleto,
'application/rtf'
).then(function() {
console.log('Success');
}, function(err) {
console.log('An error occurred: ' + JSON.stringify(err));
});
}
}else{
var directoryReader = fileSystem.createReader();
console.log("directoryReader "+JSON.stringify(directoryReader));
directoryReader.readEntries(function(entries) {
// console.log("entries "+entries);
deferred.resolve(entries);
console.log("result "+ JSON.stringify(entries));
}, function(error) {
deferred.reject(error);
});
}
}, function(error) {
deferred.reject(error);
});
return deferred.promise;
}
};
return File;
});
Every element in your files array should have a parameter file.fullPath which you can parse for the file extension. For example, split by . and check the last substring.
EDIT
Or use the file.name parameter, which contains the file name without the path.
Then just set it for every entry in the array like $scope.files[i].extension = extension; and use file.extension in your HTML with ngClass or ngSrc directive, for example.
I want to send $stateparams.id along with the below,
HTML:
<ion-refresher pulling-text="Pull to refresh..." on-refresh="vm.loadList(true)">
</ion-refresher>
<ion-list>
<ion-item class="item-remove-animate item-thumbnail-left item-icon-right" ng-repeat="data in vm.menuItems" href="#/app/menu-detail/{{data._id}}" type="item-text-wrap">
<img ng-src="app/data/images/{{data.imageUrl}}">{{data.categoryName}} <br />
<p ng-show="{{data.is_recommended}}"><span class="gem-label warning">Chef Special</span></p>
<i class="icon ion-chevron-right icon-accessory"></i>
</ion-item>
</ion-list>
Controller:
vm.loadList = function (forceRefresh) {
appealityApi.getMixedMenu(forceRefresh,$stateParams).then(function (data) {
vm.menuItems = data
}).finally(function () {
$scope.$broadcast('scroll.refreshComplete');
I tried as below but the id is not passing to the service(appealityApi),
var params = {
id : $stateParams.id,
}
vm.loadList = function (forceRefresh,params) {
appealityApi.getMixedMenu(forceRefresh,params).then(function (data) {
vm.menuItems = data
}).finally(function () {
$scope.$broadcast('scroll.refreshComplete');
});
};
});
};
my service is as below ,
function getMixedMenu(forceRefresh,params) {
$ionicLoading.show({ template: 'Loading...' })
if (typeof forceRefresh === "undefined") { forceRefresh = false; }
var deferred = $q.defer(),
cacheKey = "basicCache",
basicData = null;
/*Grab from cache only if this is not a force refresh*/
if (!forceRefresh) {
basicData = basicDataCache.get(cacheKey);
$ionicLoading.hide();
}
if (basicData) {
console.log("Found data inside cache", basicData)
deferred.resolve(basicData);
$ionicLoading.hide();
} else {
$ionicLoading.show({ template: 'Loading...' })
$http.get(SERVER_URL + '/api/templates/getCategories?appId='+$rootScope.appId+'&mainId='+params.id)
.success(function(data) {
console.log('Received data via HTTP');
basicDataCache.put(cacheKey, data);
$ionicLoading.hide();
deferred.resolve(data);
console.log(data);
}).error(function(err) {
$ionicLoading.hide();
console.log('Error while making http call.');
deferred.reject();
});
}
return deferred.promise;
};
The id returns undefined, I tried everything in the stack-overflow but nothing is working for me
Try the following. See what you get error in log, and i will modify it
as per your need.
var idRequired = $stateParams.id //log the $stateParams.id just incase
vm.loadList = function(forceRefresh) {
appealityApi.getMixedMenu(
forceRefresh, idRequired)
.then(function(data) {
vm.menuItems =
data
}).finally(function() {
$scope.$broadcast(
'scroll.refreshComplete'
);
});
};
And, in Your Service:
function getMixedMenu(forceRefresh,
idRequired) {
console.log(idRequired); //make sure the idRequired is available.
$ionicLoading.show({
template: 'Loading...'
})
if (typeof forceRefresh ===
"undefined") {
forceRefresh = false;
}
var deferred = $q.defer(),
cacheKey = "basicCache",
basicData = null;
/*Grab from cache only if this is not a force refresh*/
if (!forceRefresh) {
basicData = basicDataCache.get(
cacheKey);
$ionicLoading.hide();
}
if (basicData) {
console.log(
"Found data inside cache",
basicData)
deferred.resolve(basicData);
$ionicLoading.hide();
} else {
$ionicLoading.show({
template: 'Loading...'
})
$http.get(SERVER_URL +
'/api/templates/getCategories?appId=' +
$rootScope.appId +
'&mainId=' + idRequired
).success(function(data) {
console.log(
'Received data via HTTP'
);
basicDataCache.put(
cacheKey,
data);
$ionicLoading.hide();
deferred.resolve(
data);
console.log(data);
}).error(function(err) {
$ionicLoading.hide();
console.log(
'Error while making http call.'
);
deferred.reject();
});
}
return deferred.promise;
};
I am using angular and the data is coming back from my api call. The problem is my list is not populating.
first partial:
<div ng-controller="CustomerController" data-ng-init="init()" class="col-md-2">
<select ng-model="customerKey" ng-options="customer.Key as customer.Value for customer in customers"></select>
</div>
second partial:
<div ng-controller="CustomerController">
<div class="col-md-2 col-md-offset-5" style="outline: 1px solid black; margin-top: 1%">
<div class="text-center">
<div class="radio-inline" ng-repeat="customerOption in customerOptions">
<input type="radio" id="{{customerOption.Value}}" name="customer" ng-change="getCustomers(customerType)" ng-model="customerType" ng-value="customerOption.Key" ng-checked="customerOption.Checked" />{{customerOption.Value}}
</div>
</div>
</div>
</div>
Controller:
var customer = angular.module('customer', []);
customer.controller('CustomerController', [
"$scope", "customerService",
function($scope, customerService) {
$scope.customerOptions = CustomerOptions;
$scope.getCustomers = function(customerType) {
$scope.showContent = false;
customerService.get(customerType).then(function (data) {
$scope.customers = data;
});
};
$scope.init = function() {
$scope.getCustomers("1");
}
}
]);
service:
app.service('customerService', [
"$http", function ($http) {
this.get = function(customerType) {
var customers;
if (customerType == "1") {
getProduction().then(function(result) { customers = result.data; });
} else if (customerType == "2") {
getTest().then(function(result) { customers = result.data; });
} else {
getAll().then(function(result) { customers = result.data; });
}
return customers;
};
var getTest = function () {
return $http({
method: "GET",
url: "api/Customer/GetTest",
})
.success(function (data) {
return data;
});
};
var getProduction = function () {
return $http({
method: "GET",
url: "api/Customer/GetProduction",
})
.success(function (data) {
return data;
});
};
var getAll = function () {
return $http({
method: "GET",
url: "api/Customer/GetAll",
})
.success(function (data) {
return data;
});
};
}
]);
If you click on any of the radio buttons, they return the appropriate list to the service function; however, I cannot get the select list to populate with that data
The problem is that the service is returning customers object instead of promise, which the controller method is looking for.
It should work if you return the promise from the service and leave the success/error handling to the controller.
app.service('customerService', [
"$http", function ($http) {
this.get = function(customerType) {
var customers;
if (customerType == "1") {
return getProduction();
} else if (customerType == "2") {
return getTest();
} else {
return getAll();
}
};
Controller:
$scope.getCustomers = function(customerType) {
$scope.showContent = false;
customerService.get(customerType).then(function (results) {
$scope.customers = results.data;
});
};
The then handlers in your customerService get() method are assigning the results of the HTTP call to a local customers variable, but this accomplishes nothing. By the time that happens, customers has already been returned to the caller as undefined, and you are most likely getting an error when you call then() on that value.
You need to return a promise from get() and the then() handlers inside get() need to have return statements in them:
this.get = function(customerType) {
if (customerType == "1") {
return getProduction().then(function(result) { return result.data; });
} else if (customerType == "2") {
return getTest().then(function(result) { return result.data; });
} else {
return getAll().then(function(result) { return result.data; });
}
};
There is quite a bit of duplication here, and this can be consolidated:
this.get = function(customerType) {
var customerPromise =
(customerType === "1") ? getProduction()
: (customerType === "2") ? getTest() : getAll();
return customerPromise.then(function (result) { return result.data; });
};