I have two drop-downs and a table.
I don't know how exactly to pass the selected value from the first drop-down to the second. Except not passing selected value to the second drop-down the first service is working fine.
My JavaScript:
var myApp = angular.module("myApp", []);
myApp.service('companiesService', ['$http', '$q', function ($http, $q) {
var currentSettings = null;
this.getList = function () {
var def = $q.defer()
if (currentSettings) {
def.resolve(currentSettings);
} else {
$http.post('GetCompanies')
.then(function (response) {
var response = $.parseJSON(response.data)
currentSettings = response;
def.resolve(currentSettings);
});
}
return def.promise;
}
}]);
myApp.service('docTypeService', ['$http', '$q', function ($http, $q) {
var docSettings = null;
this.getList = function () {
var def = $q.defer()
if (docSettings) {
def.resolve(docSettings);
} else {
$http.post('GetDocTypes')
.then(function (response) {
var response = $.parseJSON(response.data)
docSettings = response;
def.resolve(docSettings);
});
}
return def.promise;
}
}]);
myApp.service('allCurrentSettingsService', ['$http', '$q', function ($http, $q) {
var allSettings = null;
this.getList = function () {
var def = $q.defer()
if (allSettings) {
def.resolve(allSettings);
} else {
$http.post('GetAllCurrentSettings')
.then(function (response) {
var response = $.parseJSON(response.data)
allSettings = response;
def.resolve(allSettings);
});
}
return def.promise;
}
}]);
myApp.controller('myController', ['$scope', 'companiesService', 'docTypeService', 'allCurrentSettingsService',
function ($scope, companiesService, docTypeService, allCurrentSettingsService) {
$scope.currentSettings = '';
companiesService.getList().then(function (value) {
$scope.currentSettings = value;
});
$scope.docSettings = '';
docTypeService.getList().then(function (value) {
$scope.docSettings = value;
});
$scope.allSettings = '';
allCurrentSettingsService.getList().then(function (value) {
$scope.allSettings = value;
});
}
]);
And my HTML`
<table>
<tr>
<td>Select a company:</td>
<td>
<div data-ng-controller="myController">
<select ng-model="dropdownvalue" ng-change="GetDocTypes(dropdownvalue)">
<option data-ng-repeat="currentSetting in currentSettings" value={{currentSetting.SCACCode}}>{{currentSetting.SCACCode}}</option>
</select>
</div>
</td>
</tr>
<tr>
<td>Enter customer: </td>
<td><div><input id="Text1" type="text" /></div></td>
</tr>
<tr>
<td>Select document:</td>
<td>
<div ng-controller="myController">
<select>
<option>Select document</option>
<option ng-repeat="docSetting in docSettings" value="{{docSetting.Doc_Type}}">{{docSetting.Doc_Type}}</option>
</select>
</div>
</td>
</tr>
</table>
`
My MVC Controller
`
public JsonResult GetDocTypes(string company)
{
var jsonString = string.Empty;
string query = "SELECT * FROM Companies WHERE CompName = #Company";
try
{
using (SqlConnection conn = new SqlConnection(connStringEbe))
{
conn.Open();
using (SqlCommand command = new SqlCommand(query, conn))
{
DataTable dt = new DataTable();
command.Parameters.Add(new SqlParameter("#Company", company));
using (SqlDataReader rdr = command.ExecuteReader())
{
dt.Load(rdr);
}
command.Parameters.Clear();
jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(dt, Formatting.None);
return Json(jsonString);
}
}
}
catch (Exception ex)
{
Console.Write(ex.ToString());
return Json(jsonString);
}
}
`
Related
I am new to Angular and MVC , and I have created a code for display
records into table view.
User can edit and delete that records by clicking the Edit and Delete
Link
but it shows me error when i click on edit link TypeError:
v2.UpdataData is not a function
and it also shows me error TypeError: $http.get is not a function
when i click on Delete Link
Can anyone help me to solve this out. Thanks in advance.
Controller.js
//update data of table
$scope.UpdataData = [];
//UpdateData();
$scope.UpdateData = function (StateMaster) {
var RetValData = DataService.UpdateStudent(StateMaster);
debugger;
getData.then(function (StateMaster) {
debugger;
StateID: $scope.StateID;
StateName: $scope.StateName;
CountryName: $scope.CountryName;
}, function () {
alert('Error in getting records');
});
}
$scope.DeleteData = [];
$scope.DeleteData = function (r, index) {
var retval = DataService.DeleteData(r.StateID).success(function (msg) {
$scope.countrydata.splice(index, 1);
alert('Student has been deleted successfully.');
}).error(function () {
alert('Oops! something went wrong.');
});
}.factory('DataService', function ($http) {
var fac={}
debugger;
fac.UpdateData= function($http)
{
return $http.get('/State/UpdateData');
}
return fac;
}).factory('DataService', function () {
var fac={}
debugger;
fac.DeleteData = function ($http)
{
return $http.get('/State/DeleteData');
}
return fac;
});
StateController.cs
public string UpdateData(StateMaster r)
{
if (r != null)
{
using (simpleEntities dbContext = new simpleEntities())
{
StateMaster lstdata = dbContext.StateMasters.Where(x => x.StateID == r.StateID).FirstOrDefault();
lstdata.StateName = r.StateName;
lstdata.CountryName = r.CountryName;
dbContext.SaveChanges();
return "Data Updated";
}
}
else
{
return "something went worng";
}
}
[HttpPost]
public string DeleteData(int id)
{
if (id != 0)
{
using (simpleEntities databContext = new simpleEntities())
{
var lsdata = databContext.StateMasters.Where(x => x.StateID == id).FirstOrDefault();
databContext.StateMasters.Remove(lsdata);
databContext.SaveChanges();
return "Data Deleted Successfully";
}
}
else {
return "Error Occured";
}
}
InsertState.cshtml
<div ng-app="MyApp" ng-controller="StateController">
<table class="table table-bordered">
<tr>
<td>Sr. No.</td>
<td>Country Name</td>
<td>State Name</td>
<td></td>
#*<td>Country Name</td>*#
</tr>
<tr ng-repeat="r in countrydata">
<td>{{$index + 1}}</td>
<td>{{r.CountryName}}</td>
<td>{{r.StateName}}</td>
#*<td>{{r.CountryName}}</td>*#
<td>
<span ng-click="UpdataData(r)" class="btnAdd">Edit</span> |
<span ng-click="DeleteData(r)" class="btnRed">Delete</span>
</td>
</tr>
</table>
</div>
there is problem in you code with this
line $scope.UpdateData = function (StateMaster
as you are trying to run fuction of your $scop but fuction is of factory so you have to try like
factory.UpdateDate
Seem like there is problem in defining factory in angular , you can try below way
var app = angular.module('myApp', []);
app.factory('testFactory', function(){
return {
sayHello: function(text){
return "Factory says \"Hello " + text + "\"";
},
sayGoodbye: function(text){
return "Factory says \"Goodbye " + text + "\"";
}
}
});
function HelloCtrl($scope, testService, testFactory)
{
$scope.fromFactory = testFactory.sayHello("World");
}
you can place your function and just try out it return you value or not
enter image description herePlease check below code.angular inbuilt filter working fine. need to filter data by using date picker Please help me for the same. screenshot attached for the reference
<div class="table-responsive">
<table class="table table-bordered table-striped ">
<thead>
<tr>
<td>RECEIPT NO</td>
<td>DATE</td>
<td>NAME</td>
<td>PLACE</td>
<td>MEDIATOR NAME</td>
<td>INTEREST RATE</td>
</tr>
</thead>
<tbody>
<tr ng-repeat="rec in records |filter:searchText |filter: date_picker">
<td>{{rec.RECEIPT_NO}}</td>
<td>{{rec.DATE}}</td>
<td>{{rec.NAME}}</td>
<td>{{rec.PLACE}}</td>
<td>{{rec.MEDIATOR_NAME}}</td>
<td>{{rec.INTEREST_RATE}}</td>
</tr>
</tbody>
</table>
</div>
Angular Code-------------------
var app = angular.module("myApp", []);
app.controller("reportingCtrl", function($scope, $http){
$scope.records = [];
$scope.ajayxCall = function() {
var url = "assets/API/api.json";
$http.get(url).then(function(response) {
$scope.records = response.data
});
};
$scope.ajayxCall();
$scope.today = function() {
$scope.dt = new Date();
};
$scope.today();
$scope.clear = function() {
$scope.dt = null;
};
$scope.toggleMin = function() {
$scope.minDate = $scope.minDate ? null : new Date();
};
$scope.toggleMin();
$scope.open = function($event) {
$event.preventDefault();
$event.stopPropagation();
$scope.opened = true;
};
$scope.dateOptions = {
formatYear: 'yy',
startingDay: 1
};
$scope.formats = ['yyyy/MM/dd', 'dd-MMMM-yyyy', 'dd.MM.yyyy', 'shortDate'];
$scope.format = $scope.formats[0];
$scope.getTime = function() {
time.getTime()
.success(function(data) {
console.log(data);
$scope.records = data.records;
})
.error(function(data, status, headers, config) {
console.log('error!');
});
};
});
Create a custom filter for date like following
.filter('DateFilter', function() {
return function(dataArray, date) {
if (!dataArray) {
return;
} else if (!date) {
return dataArray;
} else {
return dataArray.filter(function(item) {
var recordDate = new Date(item.DATE);
var term = recordDate.getFullYear() === date.getFullYear() &&
recordDate.getMonth() === date.getMonth() &&
recordDate.getDate() === date.getDate();
return term;
});
}
};
})
You can call this filter like
<tr ng-repeat="rec in records |filter:searchText | DateFilter: date_picker">
Its my code:
.controller("GetAllAuthors", function ($scope, $http) {
$http.get('http://localhost:8080/authors')
.then(function (response) {
$scope.authors = response.data;
});
$scope.edit = function (index) {
for (var i = 0; i < $scope.authors.length; i++) {
if ($scope.authors[i].id == index) {
$scope.object = $scope.authors[i];
break;
}
}
}
})
Html view:
<tbody ng-repeat="author in authors">
<td><input type="button" ng-click="edit(author.id)" value="Edit"/></td>
<div ng-controller="GetAllAuthors">
{{object.id}} // <--- doesn't display it
</div>
It's not working. I can't use date binding with my object. How fix it?
You need to put http inside edit method.
.controller("GetAllAuthors", function ($scope, $http) {
$scope.edit = function (index) {
$http.get('http://localhost:8080/authors')
.then(function (response) {
$scope.authors = response.data;
for (var i = 0; i < $scope.authors.length; i++) {
if ($scope.authors[i].id == index) {
$scope.object = $scope.authors[i];
break;
}
}
});
}
})
Try this
Initialize $scope.object outside the function.
I am trying to apply filter to my data table.
<div class="widget-content table-container" ng-controller="getEmployeesController" style="overflow:auto">
<table ng-table="employeesList" show-filter="true" class="table table-striped table-bordered">
<tr ng-repeat="employee in $data">
<td data-title="'#'">
{{ (itemsPerPage * (pageNumber-1)) + $index+1 }}
</td>
<td data-title="'Name'" sortable="'Name'" filter="{ 'firstName+lastName': 'text' }">
{{employee.firstName +""+employee.lastName}}
</td>
<td data-title="'First Name'" sortable="'firstName'" filter="{ 'firstName': 'text' }">
{{employee.firstName}}
</td>
<td data-title="'Last Name'" sortable="'lastName'" filter="{ 'lastName': 'text' }">
{{employee.lastName}}
</td>
</tr>
</table>
</div>
The filtering works fine in 2nd and 3rd . I want a TD where the first name and second name is concatenated.
App.js
//Datatable
myApp.factory('dataTable', ['$filter', 'ngTableParams', '$rootScope', function ($filter, ngTableParams, $rootScope) {
var factoryDefinition = {
render: function($scope, config, componentId, data) {
if (!config) config = { filter: { 'firstName': $rootScope.mysearch } };
var config = angular.extend({}, {page:1, count:10}, config)
$scope[componentId] = new ngTableParams(config, {
total: data.length, // length of data
getData: function ($defer, params) {
// organize filter as $filter understand it (graph object)
var filters = {};
var val = $rootScope.mysearch;
var key = "firstname";
$rootScope.mysearch = "";
angular.forEach(params.filter(), function (val, key) {
var filter = filters;
var parts = key.split('.');
for (var i = 0; i < parts.length; i++) {
if (i != parts.length - 1) {
filter[parts[i]] = {};
filter = filter[parts[i]];
}
else {
filter[parts[i]] = val;
}
}
});
// use build-in angular filter
var filteredData = params.filter() ?
$filter('filter')(data, filters) :
data;
var orderedData = params.sorting() ?
$filter('orderBy')(filteredData, params.orderBy()) :
data;
params.total(orderedData.length); // set total for recalc pagination
$defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count()));
$scope.pageNumber = params.page();
$scope.itemsPerPage = params.count();
}
});
}
}
return factoryDefinition;
}
]);
myApp.filter('customFilter', ['$filter', function ($filter) {
var filterFilter = $filter('filter');
var standardComparator = function standardComparator(obj, text) {
text = ('' + text).toLowerCase();
return ('' + obj).toLowerCase().indexOf(text) > -1;
};
return function customFilter(array, expression) {
function customComparator(actual, expected) {
var isBeforeActivated = expected.before;
var isAfterActivated = expected.after;
var isLower = expected.lower;
var isHigher = expected.higher;
var higherLimit;
var lowerLimit;
var itemDate;
var queryDate;
if (ng.isObject(expected)) {
//exact match
if (expected.distinct) {
if (!actual || actual.toLowerCase() !== expected.distinct.toLowerCase()) {
return false;
}
return true;
}
//matchAny
if (expected.matchAny) {
if (expected.matchAny.all) {
return true;
}
if (!actual) {
return false;
}
for (var i = 0; i < expected.matchAny.items.length; i++) {
if (actual.toLowerCase() === expected.matchAny.items[i].toLowerCase()) {
return true;
}
}
return false;
}
//date range
if (expected.before || expected.after) {
try {
if (isBeforeActivated) {
higherLimit = expected.before;
itemDate = new Date(actual);
queryDate = new Date(higherLimit);
if (itemDate > queryDate) {
return false;
}
}
if (isAfterActivated) {
lowerLimit = expected.after;
itemDate = new Date(actual);
queryDate = new Date(lowerLimit);
if (itemDate < queryDate) {
return false;
}
}
return true;
} catch (e) {
return false;
}
} else if (isLower || isHigher) {
//number range
if (isLower) {
higherLimit = expected.lower;
if (actual > higherLimit) {
return false;
}
}
if (isHigher) {
lowerLimit = expected.higher;
if (actual < lowerLimit) {
return false;
}
}
return true;
}
//etc
return true;
}
return standardComparator(actual, expected);
}
var output = filterFilter(array, expression, customComparator);
return output;
};
}]);
Controller
myApp.controller('getEmployeesController', ['$scope', 'employeeServices', 'dataTable', '$window', '$timeout', '$filter', '$rootScope', 'ngDialog',
function ($scope, employeeServices, dataTable, $window, $timeout, $filter, $rootScope, ngDialog) {
employeeServices.getEmployees().then(function (result) {
$scope.data = result.data;
});
The concatenated TD is not getting filtered properly. What should I do to make it functional?
Found the solution,
Created a new property in the collection and then set it to concatenated object to resolve the issue.
Controller :
myApp.controller('getEmployeesController', ['$scope', 'employeeServices', 'dataTable', '$window', '$timeout', '$filter', '$rootScope', 'ngDialog',
function ($scope, employeeServices, dataTable, $window, $timeout, $filter, $rootScope, ngDialog) {
employeeServices.getEmployees().then(function (result) {
$scope.data = result.data;
angular.forEach(result.data, function (value, key) {
if (value.lastName == undefined) {
}
var fullName = value.firstName + '' + ((value.lastName != undefined) ? (value.lastName) : (''));
result.data[key].fullName = fullName;
});
});
HTML:
<td data-title="'Name'" sortable="'firstName'" filter="{ 'fullName': 'text' }" style="width:100px">
{{employee.fullName}}
</td>
I wrote script to test passing variables between controllers, so i define a service and declare variable on it getContents, then pass it to next controller personController, but something goes wrong, this is my script:
<script>
angular.module("app", []).service("personService", function () {
var getContents = {};
})
.controller("personController", function ($http, $scope, personService) {
$scope.GetContents = function () {
$http.get("/Home/Get").success(function (data) {
debugger;
personService.getContents = data;
$scope.Persons = data;
});
}
$scope.Save = function () {
$http.post("AddPerson",$scope.model).success(function (status) {
debugger;
console.log('status =', status);
$scope.ShowForm = false;
$scope.GetContent();
});
}
$scope.AddPerson = function () {
$scope.ShowForm = true;
$scope.model = {};
}
});
</script>
what is wrong?
NOTE: when i remove the Service, the controller work properly and get data from /Home/Get.
Edit: this is my edit:
<script>
angular.module("app", []).service("personService", function () {
var Content = {};
return {
getContent: function () {
return Content;
},
setContent: function (value) {
Content = value;
}
};
})
.controller("personController", function ($http, $scope, personService) {
$scope.GetContents = function () {
debugger;
$http.get("/Home/Get").success(function (data) {
debugger;
console.log("successData :", data); //console did not log
personService.setContent(data);
console.log("ServiceData:",personService.getContent()) //console did not log too
$scope.Persons = data;
});
}
$scope.AddPerson = function () {
$scope.ShowForm = true;
$scope.model = {};
}
});
</script>
and this is my html:(for more help)
<div ng-app="app">
<div class="container" ng-controller="personController" ng-init=" GetContent()">
<div ng-show="!ShowForm">
<table class="table">
<thead>
<tr>
<th>Firstname</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="person in Persons">
<td>{{person.Name}}</td>
</tr>
</tbody>
</table>
</div>
</div>
you have to return service
service
angular.module("app", []).service("personService", function () {
var content = {};
var person = {
setContent :function(item){
content = item;
}
getContent : function(){
return content;
};
};
return person;
})
Controller
.controller("personController", function ($http, $scope, personService) {
$scope.GetContents = function () {
$http.get("/Home/Get").success(function (data) {
debugger;
personService.setContent(data); // set content to service..
$scope.Persons = data;
});
}
$scope.Save = function () {
$http.post("AddPerson",$scope.model).success(function (status) {
debugger;
console.log('status =', status);
$scope.ShowForm = false;
personService.getContent(); // get content from service..
});
}
$scope.AddPerson = function () {
$scope.ShowForm = true;
$scope.model = {};
}
define personService.getContent() to $scope variable to display on view page.
$scope.content = personService.getContent();