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;
}]);
I'm currently working on a project that I need to sort the response by category and subcategory using Angular.
My controller currently looks like:
function($http, $stateParams) {
let vm = this;
$http({
method: 'GET',
url: url,
timeout: 10000,
contentType: "application/json;odata=verbose",
headers: {"Accept": "application/json;odata=verbose"},
params: {},
}).then(function(data, status, headers, config) {
let documents = data.data.d.results;
$.each(documents, function(i, item){
vm.data = sortDocuments(documents);
})
}).catch(function(error) {
console.log(error);
});
function sortDocuments(documents) {
return _.sortBy(documents, item => {
return {
category: item.Category,
subcategory: item.Subcategory,
documentURL: item.EncodedAbsUrl,
tags: item.Tags
}
})
};
})
I need to sort the category and subcategories in my view, but not sure how to go about doing it. My template partial currently looks like:
<div uib-accordion-group class="panel-default" heading="Subcategory Name">
<table class="table">
<thead>
<tr>
<th>Name</th>
<th>Tags</th>
<th>Link</th>
</tr>
</thead>
<tbody ng-show="item.subcategory == 'Subcategory Name'" ng-repeat="item in documents.data">
<tr>
<td>
<p>{{ item.name }}</p>
</td>
<td>
<p>{{ item.tags.results }}</p>
</td>
<td>
<a href="{{ item.documentURL }}">Open
Document</a>
</td>
</tr>
</tbody>
</table>
</div>
Can anyone tell me what I'm missing in order to sort the view by category and subcategory?
I'm not sure why you're using _.map there. _.sortBy should do what you need.
http://underscorejs.org/#sortBy
this should be pretty close:
vm.data = _.sortBy(data.data.d.results, document => { return document.Category + document.Subcategory } )
i want to pass the json data from controller to angularjs..i have tried the below code but just only show the table header don't show my product data..below put my code..
this is my angularjs code..
$scope.ViewPro = function () {
$http({ method: 'GET', url: 'AddToCart/ProList' }).
success(function (p) {
debugger;
console.log(p);
$scope.Products = p; // Response Data
$location.path('/ViewProduct');
}).
error(function (data) {
alert(data + "Error");
console.log(data);
});
};
this is my json controller method..
public JsonResult ProList()
{
var ProductList = db.tblProducts.ToList();
var Products = ProductList.Select(d => new
{
d.ProductId,
d.ProductName,
d.Price,
d.Descripation,
d.SEOURL,
d.Image,
d.IsPubliesd,
}).ToList();
return Json(Products, JsonRequestBehavior.AllowGet);
}
this is my routeProvider
.when('/ViewProduct', { templateUrl: 'AddToCart/ViewProduct' })
this is my view..
#model IEnumerable<AJSWithShoppingCart.Models.tblProduct>
<div ng-app="MyApp" ng-controller="AddToCart" ng-model="AddToCart">
<div class="table-responsive">
<table class="table table-striped table-bordered">
<tr>
<td align="center"><b>ProductId</b></td>
<td align="center"><b>ProductName</b></td>
<td align="center"><b>Descripation</b></td>
<td align="center"><b>Price</b></td>
<td align="center"><b>SEOURL</b></td>
<td align="center"><b>IsPubliesd</b></td>
<td align="center"><b>AddToCart</b></td>
</tr>
<tr ng-repeat="Product in Products">
<td ng-bind="Product.ProductId"></td>
<td>{{Product.ProductName}}</td>
<td>{{Product.Descripation}}</td>
<td>${{Product.Price}}.00</td>
<td>{{Product.SEOURL}}</td>
<td>{{product.ispubliesd}}</td>
</tr>
</table>
</div>
</div>
I want data to appear in table according to selected value. I want to bind data to table after data is fetched when ng-change of dropdownlist is triggered
<div ng-app="myapp" ng-controller="prodctrl" >
<select id="BrandDropdown" class="InstanceList" ng-change="GetBrandProd()" ng-model="Products">
<option>Select Brand</option>
#if (ViewBag.dataset != null)
{
foreach (string str in (string[])ViewBag.dataset)
{
<option value='#str.Split('/')[0]'>#str.Split('/')[1]</option>
}
}
</select>
<table ng-model="Products">
<tr ng-repeat="P in Products track by $index">
<td >{{x.Id}}</td>
<td >{{X.Rank}}</td>
<td >{{x.Name}}</td>
</tr>
</table>
</div>
this the code
var app = angular.module('myapp', []);
app.controller('prodctrl', function ($scope, $http) {
$scope.GetBrandProd = function () {
var Id = $('#BrandDropdown').val();
$http({
method: "GET",
url: "/Home/GetProdBrand",
params: {
id:Id
}
})
.success(function (response) {
$scope.Products = response.records;
});
}
})
I am able to get the data successfully in response.records. but after i get data nothing happens
What I'm looking for is to learn a proper way to build a webapp. I already built some things, but I've got to a point where I need to reuse some data and with ng-controllers, it's getting harder.
I already know controllers are not the best option, so I tried to jump to directives, based on some articles I've read. But none of them has helped me.
So, let me try to describe it.
Description
I'm building a dashboard, where i have some clients (add/edit/del), projects (which invole one or more clients), agenda, configuration, financials, etc..
I've built a lot of things already, but for example:
On the home page I'm displaying a table with the last 5 clients added to the app, also a table with the last 5 projects added to the app. Then, on the clients.html page, I display the whole table, same goes for projects, on the project.html. Both with just 3-4 fields with name, tel and email. Then on the individual client page, i display the whole information about that client. Such as address, email, contacts, observations, etc. And also a list of projects he is involved.
So what I have is something like this:
app.js
myApp.controller('ClientesCtrl', function ($scope, $http, $routeParams) {
$scope.pagename = "Clientes";
$scope.get_cliente = function() { //Function - Get Cliente
$http.get("scripts/data/clientes.json")
.success( function(data) {
$scope.pagedClientes = data;
})
.error(function(data) {});
};
$scope.add_cliente = function() { //Function - Add Cliente
$scope.formprevent = true;
$http.post('scripts/php/db.php?action=add_cliente',
{
'cod': $scope.cad.cod,
[... more data ...]
}
)
.success(function (data, status, headers, config) {})
.error(function (data, status, headers, config) {});
};
});
Same goes for projects, each one with it's controller.
My folder/File organizations is very very simple (since I don't know what I can put in different files, or even how to call it back). It's something like this:
-index.html
-scripts
--js
---angular.min.js
---angular-route.min.js
--app
---app.js
-content
--home.html
--clients.html
--projects.html
The Problem
The problem starts when i need to show those data in a lot of pages.
For example in the home page, i have a list with a resume of the main data, such as total clients, total projects, and it's like this:
<div class="col-md-3" ng-controller="ClientesCtrl">
<div ng-init="get_cliente();>
<div class="label">{{pagedClientes.length || "00"}}</div>
<div class="text">clientes totais</div>
</div>
</div>
<div class="col-md-3" ng-controller="ProjectsCtrl">
<div ng-init="get_projects()">
<div class="label">{{pagedProjects.length || "00"}}</div>
<div class="text">Processos totais</div>
</div>
</div>
<div class="col-md-3">
<div>
<div class="label">00</div>
<div class="text">Processos abertos</div>
</div>
</div>
<div class="col-md-3">
<div>
<div class="label">00</div>
<div class="text">Compromissos abertos</div>
</div>
</div>
<div class="table-body" ng-controller="ClientesCtrl">
<table ng-init="get_clients()">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Options</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="client in pagedClients | limitTo:-5 | orderBy:'-id'" ng-if="pagedClients.length > 0">
<td>{{cliente.cod}}</td>
<td>{{cliente.nm_client}}</td>
<td>
<a class="bt-t bt-inf" href="#/detcliente/{{cliente.id}}"></a>
</td>
</tr>
<tr ng-if="pagedClientes.length == 0">
<td colspan="3"><h3>No client</h3></td>
</tr>
</tbody>
</table>
</div>
<div class="table-body" ng-controller="ProjectsCtrl">
<table ng-init="get_projects()">
<thead>
<tr>
<th>ID</th>
<th>Project</th>
<th>Options</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="project in pagedProjects | limitTo:-5 | orderBy:'-id'" ng-if="pagedProjects.length > 0">
<td>{{project.cod}}</td>
<td>{{project.nm_cliente}}</td>
<td>
<a class="bt-t bt-inf" href="#/detproject/{{project.id}}"></a>
</td>
</tr>
<tr ng-if="pagedClientes.length == 0">
<td colspan="3"><h3>No project</h3></td>
</tr>
</tbody>
</table>
</div>
So, basically, I need to add the controller in each block I need to display that data, also I have to 'init' the function to get the data again. This is a simple example, but I think it was enough to show what I need to solve.
It's worse when I need to show the individual client, with only their projects. So before I get crazy with all of those controllers, I want to know how is the best way to put up the logic, the folder/file organization, the code organization. Is it better to use a directive? to make the directive call a controller? Call multiple controllers? Or what?
You need to use services to fetch the data: https://docs.angularjs.org/guide/services. For your code it would look something like this:
app.factory('clients', function ($http) {
var getClients = function() { //Function - Get Cliente
return $http.get("scripts/data/clientes.json")
.success( function(data) {
return data;
})
.error(function(data) {});
};
var add_cliente = function(cad) { //Function - Add Cliente
$http.post('scripts/php/db.php?action=add_cliente',
{
'cod': cad.cod,
[... more data ...]
}
)
.success(function (data, status, headers, config) {})
.error(function (data, status, headers, config) {});
};
return {
getClients: getClients,
add_cliente: add_cliente
}
})
You can then inject the service in a controller and use the functions in your controller:
app.controller('Ctrl', function (clients, $scope) {
clients.getClients().then(function (data) {
$scope.myClients = data;
});
});
Read the client data on initialization of the controller - not need to use a ng-init.
myApp.controller('ClientesCtrl', function ($scope, $http, $routeParams) {
$scope.pagename = "Clientes";
$http.get("scripts/data/clientes.json")
.success( function(data) {
$scope.pagedClientes = data;
})
.error(function(data) {});
$scope.add_cliente = function() { //Function - Add Cliente
$scope.formprevent = true;
$http.post('scripts/php/db.php?action=add_cliente',
{
'cod': $scope.cad.cod,
[... more data ...]
}
)
.success(function (data, status, headers, config) {})
.error(function (data, status, headers, config) {});
};
});
Controllers can be nested. Define the controller on a div which wraps the area where you need the client data. Same for the ProjectsController. You could even merge the 2 controllers in one.
<div ng-controller="ClientesCtrl">
<div class="col-md-3" >
<div ng-init="get_cliente();>
<div class="label">{{pagedClientes.length || "00"}}</div>
<div class="text">clientes totais</div>
</div>
</div>
....