Selecting default value using ngModel ngRepeat, ngOptions - angularjs

Hopefully someone can help.
I am developing an application using HTML AngularJs which uses ng-repeat,ng-options and ng-model and populates multiple rows based on the data in the database for a user. Each row has static data coming from DB (returned as object via restAPI) and dynamic select option for user selection. Select option is hardcoded in app.js and linked to model on HTML for DB update upon selection using update button. Each row has its own button and i can see update function is working at row level.
I want to set the default value of the drop down list dynamically as value of an element coming from database. Object is same as one being used to populate rows with static data .
Code is in the fiddle at https://jsfiddle.net/6j88L61y/4/
HTML below
<body>
<h1 align="center">User Tracker</h1>
<div ng-controller="MainController as main">
<div>
<p>Please Enter ID </p>
<p>
<input type="text" ng-model="main.model.userName"></input>
<button ng-click="main.model.getOrgList()">List State List</button>
</p>
</div>
<hr ng-show="main.model.formSubmitted"></hr>
<div>
<table class="table table-bordered" border="1">
<thead>
<tr>
<th>ID</th>
<th>User Name</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="org in main.model.orgList" id="{{org.id}}">
<td>{{org.id}}</td>
<td align="center">{{org.user}}</td>
<td align="center">
<select ng-model="main.model.selectedRecord.appCurrentStateSelected[$index]" ng-options="option.value as option.value for option in main.model.appCurrentStateList" ></select>
</td>
<td>
<button ng-click="main.model.updateAppDetailsList({id:org.id,userName:org.name,appCrntState:main.model.selectedRecord.appCurrentStateSelected})">Update</button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</body>
JS
"use strict";
angular.module('myApp',[]);
angular.module('myApp').service('AppModel', function( $http) {
this.userId='';
this.userName ="";
this.formSubmitted="";
this. selectedRecord ={appCurrentStateSelected:''};
this.appCurrentStateList =[{name: 'New',value:'New',id:1}, {name: 'InUse',value:'InUse',id:2},{name: 'Inactive',value:'Inactive',id:3},{name: 'Deleted',value:'Deleted',id:4}];
this.submittedAppDetailsList=[];
console.log(' json sample:'+this.submittedAppDetailsList);
var path = 'home';
var currentProtocol = location.protocol;
var host =location.host;
var apiHost = currentProtocol+'//'+host+'/api/';
console.log('API url is : ' +apiHost);
// Get method
this.getOrgList = function() {
var path = 'home/userid';
console.log(this.userName);
console.log(this.selectedRecord);
$http.get(apiHost+path+'/'+this.userName+'/')
.then(function(response) {
this.orgList =response.data;
this.formSubmitted = true;
console.log(response.data);
}.bind(this),
function(response) {
console.log(response.data);
});
}
// Post method
this.updateAppDetailsList = function(appdetailsList) {
var path = 'home/update';
console.log(this.selectedRecord);
$http.post(apiHost+'home/update/',appdetailsList)
.then(function(response) {
this.submittedAppDetailsList.push(response.data);
this.formSubmitted = false;
console.log(response.data);
}.bind(this),
function(response) {
console.log('Error : '+response.data);
});
}
});
angular.module('myApp').controller('MainController', ['AppModel', function (AppModel) {
this.model = AppModel;
}]);

Related

angularjs with jquery datatable search button does not work

When i try to use jquery datatable with angularjs, search button doesn't work. but if i bind the data using pure asp.net mvc by actionresult method, it works correctly.
I bind the data from user-role.js and i'm using ng-repeat to bind them.
my angularjs version is 1.7.2
jquery.datatble version is 1.10.16
cshtml codes below.
<script type="text/javascript" src="~/Scripts/app/user-role.js"></script>
<div ng-app="userRoleGridApp" ng-controller="userRoleGridCtrl">
<div class="container">
<div class="row">
<div class="col-md-9">
<div class="table-responsive">
<table class="table" id="user-table">
<thead>
<tr>
<th>UserId</th>
<th>User Name</th>
<th>Name Surname</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="x in Users track by $index">
<th>{{x.UserId}}</th>
<th>{{x.UserName}}</th>
<th>{{x.NameSurname}}</th>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function () {
$('#user-table').DataTable({
dom: 'Bfrtip',
buttons: [
'copyHtml5',
'excelHtml5',
//'csvHtml5',
'pdfHtml5'
]
});
});
</script>
Js side
var app = angular.module("userRoleGridApp",
['ngAnimate',
'ngRoute']);
var baseUrl = location.origin;
app.controller("userRoleGridCtrl", function ($scope, $http) {
$scope.Users = {};
initUser();
function initUser() {
$http({
method: "get",
url: baseUrl + "/UserRole/GetUsers"
}).then(function (response) {
$scope.Users = response.data;
}, function () {
alert("Error Occur");
});
}
});

Error message Argument 'angularCrud' is not a function, got undefined in MVC4 with AngularJS

Hi I am developing small Crud operation application in MVC4 with angularJS. I am getting error message as below.
Argument 'angularCrud' is not a function, got undefined
I am refering below article.
http://www.codeproject.com/Articles/1032226/CRUD-Operation-in-ASP-NET-MVC-and-AngularJS
This is my controller code.
public ActionResult Index()
{
return View();
}
public JsonResult GetAllGroups()
{
using (C3KYCEntities db = new C3KYCEntities())
{
var groupList = db.tm_grp_group.ToList();
return Json(groupList, JsonRequestBehavior.AllowGet);
}
}
This is my view code.
<div ng-controller="angularCrud">
<div ng-app="angularCrud">
<div class="divList">
<p><b><i>Group List</i></b></p>
<table class="table table-hover">
<tr>
<td><b>ID</b></td>
<td><b>Name</b></td>
<td><b>Desc</b></td>
<td><b>IsActive</b></td>
</tr>
<tr ng-repeat="group in groups">
<td>
{{group.grp_id}}
</td>
<td>
{{group.grp_name}}
</td>
<td>
{{group.grp_description}}
</td>
<td>
{{group.grp_isactive}}
</td>
<td>
<span ng-click="editgroup(group)" class="btn btn-primary">Edit</span>
<span ng-click="deletegroup(group)" class="btn btn-danger">Delete</span>
</td>
</tr>
</table>
</div>
</div>
</div>
This is my Module.js
var app = angular.module('angularCrud',[]);
This is my Service.js
app.service("crudAJService", function ($http) {
alert("Hi");
this.getGroups = function () {
return $http.get("Home/GetAllGroups");
};
Here my alert is not firng.
This is my controller code.
app.controller("angularCrud", function ($scope, crudAJService) {
$scope.divGroup = false;
alert("Hi");
GetAllGroups();
function GetAllGroups() {
var getGroupData = crudAJService.getGroups();
getGroupData.then(function (group) {
alert("Hi");
$scope.groups = group.data;
}, function () {
alert('Error in getting group records');
}
);
}
});
I stuck in Module.js. Execution will not go further and I am getting error as Argument 'angularCrud' is not a function, got undefined. Can someone tell me Where I am going wrong in the above code? Thank you all.
Try to change your module name rather than having same name for controller and module,
var app = angular.module('Crud',[]);
Also ng-controller should come after ng-app
<div ng-app="Crud">
<div ng-controller="angularCrud">

AngularJS NG-Repeat Select and set selected on page load?

I am generating a grid thru Angular and each row will have a dropdown. I want the dropdown to populate with data from the server which is working but during page load, it needs to set the selected item of each dropdown to the value of the property it's bound to. Simple example below...
Class CategoryField
ID
Name
CategoryID = 2
Select
Option1 text=Category A value=1
Option2 text=Category B value=2 <--- This item should be selected on load.
The code i have appears to have a selected attribute on an item in each dropdown from page source but the dropdown is loading and selecting the blank item angular adds. Code below for grid...UPDATED CODE BELOW
<div ng-app="CategoryFieldsApp">
Search:<input ng-model="search" type="text" placeholder="Search" />
#using (Html.BeginForm("CategoryFields", "Maintenance", FormMethod.Post))
{
<div ng-controller="CategoryFieldsCtrl">
<table class="table table-striped table-hover">
<thead>
<tr>
<th></th>
<th width="200">Category</th>
<th ng-click="sort('Name')" width="200">Name</th>
<th width="150">Active</th>
</tr>
</thead>
<tbody id="CategoryFieldGrid">
<tr dir-paginate="categoryField in categoryFields|orderBy:sortKey:reverse|filter:search|itemsPerPage:10">
<td>
<input type="hidden" name="CategoryFields[{{$index}}].CategoryFieldID" ng-model="categoryField.CategoryFieldID" />
</td>
<td>
<input class="hdnCategoryID" type="hidden" name="CategoryFields[{{$index}}].CategoryID" />
<select ng-model="categoryField.CategoryID" ng-options="category.CategoryID as category.Name for category in categories"></select>
</td>
<td>
<input type="text" name="CategoryFields[{{$index}}].Name" ng-model="categoryField.Name" />
</td>
<td>
<input type="checkbox" class="active checkBox checkbox-inline" value="{{categoryField.Active}}" ng-model="categoryField.Active" name="CategoryFields[{{$index}}].Active" />
</td>
<td>
<input type="button" ng-click="remove($index)" value="Remove" />
</td>
</tr>
</tbody>
</table>
<dir-pagination-controls max-size="5"
direction-links="true"
boundary-links="true">
</dir-pagination-controls>
<br />
<a class="btn btn-default" ng-click="add()">Add Category Field</a>
<input class="btn-primary btn-sm" type="submit" value="Save" />
</div>
}
<script>
var App = angular.module('CategoryFieldsApp', ['angularUtils.directives.dirPagination']).controller('CategoryFieldsCtrl', function ($scope, $http) {
$http.get("#Url.Action("GetCategoryFields", "Maintenance")").success(function (response) {
$scope.categoryFields = response; //ajax request to fetch data into $scope.data
});
$http.get("#Url.Action("GetCategories", "Maintenance")").success(function (response) {
$scope.categories = response; //ajax request to fetch data into $scope.data
});
$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
}
$scope.remove = function (index) {
$scope.categoryFields.splice(index, 1);
};
$scope.add = function () {
$scope.categoryFields.push({
CategoryFieldID: 0,
CategoryID: 0,
Name: '',
Active: true,
ShowRemove: true
});
};
});
//$(document).ready(function () {
// $('#CategoryFieldGrid tr').each(function (i, row) {
// var categoryID = $(row).find('.hdnCategoryID').val();
// console.log(categoryID);
// $(row).find('.ddlCategories').val(categoryID);
// });
// $('.ddlCategories').on('change', function (e) {
// var hidden = $(e.target).closest('tr').find('.hdnCategoryID');
// $(hidden).val($(e.target).closest('tr').find('.ddlCategories').val());
// });
//});
Have you considered using ng-options? It could be used to replace the explicit definition of your options:
<select ng-model="categoryField.CategoryID" ng-options="category.CategoryID as category.Name for category in categories"></select>
if you break down the expression we pass to ng-options, we're setting the value of the selected item to the CategoryID property, the visible name of each option to the category Name property, and we're passing in all the categories defined $scope.categories as options:
"category.CategoryID as category.Name for category in categories"
Here's a working example I put together: http://plnkr.co/edit/CXZaUYfqcIv7PbeUrT9j?p=preview
I was able to figure out the other side of the bindings so that the mvc model was updated for post back. I simply created a hidden field that was bound to the same property. When angular's ng-model updates, it updated the value of the hidden field also. Below is the syntax for those who needs it.
<input class="hdnCategoryFieldID" type="hidden" name="CategoryFieldApprovers[{{$index}}].CategoryFieldID" value="{{categoryFieldApprover.CategoryFieldID}}" />
<select ng-model="categoryFieldApprover.CategoryFieldID" ng-options="categoryField.CategoryFieldID as categoryField.Name for categoryField in categoryFields"></select>

AngularJS - Not update table-pagination after http-get success's event

i have a problem. I'm using AngularJs with WebService-Rest, and can't update some table after the call HTTP-GET to WebService. I did tested everything but i can't get it.
Next, i attach the code. Thanks!
HTML:
...
<div class="row" ng-app="SIGA" ng-controller="CreateTable">
<div class="container-fluid">
<table class="table table-striped">
<tbody>
<tr>
<td>Buscar</td>
<td><input type="text" ng-model="search.nombre" /></td>
</tr>
<tr ng-repeat="e in estaciones | filter:paginate| filter:search" ng-class-odd="'odd'">
<td>
<button class="btn">
Detalle
</button>
</td>
<td>{{e.nombre}}</td>
</tr>
</tbody>
</table>
<pagination total-items="totalItems" ng-model="currentPage"
max-size="5" boundary-links="true"
items-per-page="numPerPage" class="pagination-sm">
</pagination>
</div>
</div>
...
JS: ...
app.controller('RestEstacion', function ($rootScope, $http) {
$http.get('http://localhost:8080/sigarest/webresources/entity.estaciones').
success(function(data) {
$rootScope.estaciones = data; UpdateTable($rootScope);
}).
error(function(status) {
alert('error:'+status);
});
});
app.controller('CreateTable', function ($scope,$rootScope) {
$rootScope.predicate = 'nombre';
$rootScope.reverse = true;
$rootScope.currentPage = 1;
$rootScope.order = function (predicate) {
$rootScope.reverse = ($rootScope.predicate === predicate) ? !$rootScope.reverse : false;
$rootScope.predicate = predicate;
};
$rootScope.estaciones = [];
$rootScope.totalItems = $rootScope.estaciones.length;
$rootScope.numPerPage = 5;
$rootScope.paginate = function (value) {
var begin, end, index;
begin = ($rootScope.currentPage - 1) * $rootScope.numPerPage;
end = begin + $rootScope.numPerPage;
index = $rootScope.estaciones.indexOf(value);
return (begin <= index && index < end);
};
});
JS (Update Function):
function UpdateTable($rootScope){
$rootScope.totalItems = $rootScope.estaciones.length;}
** Original Answer (what comments refer to) **
I think you are assigning the get response object rather than the data inside it. Try this:
success(function(response) {
$rootScope.estaciones = response.data;
UpdateTable($rootScope);
}).
** EDIT **
Now that we have established that you are returning data from the API, the real issue appears to be the double controller using $rootScope as a bridge, which can work but is a bit of an anti-pattern in Angular.
The first controller in your app is trying to act like a service, and so really needs to be converted into one. Here is some SAMPLE PSUEDO CODE to give the idea. I do not fully understand your code, like the pagination directive. There should be a click handler in the pagination directive that would call the service method changePagination and pass in the new page number. There should be no need for $rootScope anywhere in this.
JS
app.service('RestEstacionService', function ($http) {
var RestEstacionService = this;
this.apiData = null;
this.tableData = null;
this.currentPage = 1;
this.numPerPage = 5;
this.url = 'http://localhost:8080/sigarest/webresources/entity.estaciones';
this.getData = function (url) {
return $http.get(url).then(function(response) {
RestEstacionService.apiData = response.data;
// do success stuff here
// figure out which page the view should display
// assign a portion of the api data to the tableData variable
})
};
this.changePagination = function (newPage) {
// do your your pagination work here
};
});
app.controller('RestEstacionController', ['$scope', 'RestEstacionService', function ($scope, RestEstacionService) {
$scope.service = RestEstacionService;
RestEstacionService.getData(RestEstacionService.url);
}]);
HTML
<div class="row" ng-app="SIGA" ng-controller="RestEstacionController">
<div class="container-fluid">
<table class="table table-striped">
<tbody>
<tr>
<td>Buscar</td>
<td><input type="text" ng-model="search.nombre" /></td>
</tr>
<tr ng-repeat="row in services.tableData | filter:paginate| filter:search" ng-class-odd="'odd'">
<td>
<button class="btn">
Detalle
</button>
</td>
<td>{{row.nombre}}</td>
</tr>
</tbody>
</table>
<pagination total-items="services.apiData.length" ng-model="services.currentPage"
max-size="5" boundary-links="true"
items-per-page="services.numPerPage" class="pagination-sm">
</pagination>
</div>

I have to display task name and owner-name id into jsp page which i am returning from spring mvc controller. But its not displaying

I am returning list of object and I have to display task name and owner name id but I am stuck what to do in controller.js and userNotification.jsp file to display those two fields. I am using MongoDB database. I chekced that data is being returned to controller. Please help.
controller.js
releaseApp.controller('UserNotificationController', function($scope, $http) {
//console.log="Inside Controller";
$scope.msg1 = "test2";
$http.get('fetchTaskForApproval').success(function (response) {
$scope.taskDetails = response;
//console.log('success');
}).error(function(status) {
// console.log(('No task created') + ': ' + status);
});
});
userNotification.jsp
<div>
<h3>Task Pending For Approval</h3>
<b>{{msg1}}</b>
<b>{{stat}}</b>
<table class="table table-bordered">
<tr>
<th class="text-center">Task</th>
<th class="text-center">Owner</th>
<th class="text-center">Authorize</th>
</tr>
<div ng-repeat="task in taskDetails">
<tr>
<td>{{task.name}}</td>
<td>{{task.owners.ownerName.id}}</td>
<td>
<label>
<input type="submit" name="approveTask" value="Approve" />
<input type="submit" name="rejectTask" value="Reject"/>
</label>
</td>
</tr>
</div>
</table>
</div>
userNotification.java
#Controller
public class UserNotificationController {
#Autowired
MongoService mongoService;
#RequestMapping(value = "/fetchTaskForApproval", method = RequestMethod.GET)
public List<TaskDAO> notification(){
System.out.println("entering notification");
List<TaskDAO> taskDAOLists=new ArrayList<TaskDAO>();
taskDAOLists = mongoService.fetchPendingTask("Assigned");
System.out.println("exiting notification");
System.out.println(taskDAOLists);
return taskDAOLists;
}
}

Resources