Am trying to import angularjs working code to react redux.
In angularjs, this code works very well for dropdown menu but am trying to have it working exactly with react redux.
Here is my issue,
In React Redux, I have success in displaying the records in dependent dropdown menu, but want I want is to get the value of
dependent(second dropdown)
menu data each time a record in the first(Parents) dropdown menu is selected
it seems that fetchRecord(){} is not selecting and calling any data
Angularjs code
<body ng-app='myapp'>
<div ng-controller="fetchCtrl">
<table>
<tr>
<td>State :</td>
<td>
//First/Parents menu
<select ng-model='state_send' ng-change='fetchRecords()'>
<option value='0'>-- Select State --</option>
<option value='1'>provision</option>
<option value='2'>chemicals</option>
<option value='3'>foods</option>
<option value='4'>sports</option>
</select>
</td>
</tr>
<tr>
<td>//Dependent/Child menu :</td>
<td>
<select >
<option value='0'>-- Select User --</option>
<option ng-repeat="user in usersList" value='{{ user.id }}' >{{ user.name }}</option>
</select>
</td>
</tr>
</table>
</div>
<!-- Script -->
<script>
var fetch = angular.module('myapp', []);
fetch.controller('fetchCtrl', ['$scope', '$http', function ($scope, $http) {
$scope.state_send = '0';
// Fetch data
$scope.fetchRecords = function(){
$http({
method: 'post',
url: 'record.php',
data: {state_send:$scope.state_send}
}).then(function successCallback(response) {
$scope.usersList = response.data;
});
}
}]);
</script>
</body>
Partially working code for React-Redux
import React from 'react';
import { Link } from 'react-router-dom';
import { connect } from 'react-redux';
import { userActions } from '../_actions';
class RecordDropdown extends React.Component {
constructor(props) {
super(props);
this.state = { us: 0};
this.state_send = 0;
}
componentDidMount() {
this.props.dispatch(userActions.getDropdown(this.state_send));
}
fetchRecord(){
this.state_send = 0;
alert(this.state_send);
this.props.dispatch(userActions.getDropdown(this.state_send));
}
render() {
const { rec, recs } = this.props;
return (
<div style={{background:'red'}} className="well col-md-6 col-md-offset-3">
//First/Parents Menu
<select name="this.state_send" id="this.state_send" value={this.state_send} onChange={this.fetchRecord} >
<option value='0'>-- Select State --</option>
<option value='1'>provision</option>
<option value='2'>chemicals</option>
<option value='3'>foods</option>
<option value='4'>sports</option>
</select>
//Child/Dependent Menu
{recs.items &&
<ul><select>
<option value='0' >--select--</option>
{recs.items.map((rec, index) =>
<option key={rec.id} value='{ rec.id }' >{ rec.name} { rec.id }</option>
)}
</select>
</ul>
}
<p>
<input type="text" className="form-control" name="this.state_send" id="this.state_send" value={this.state_send} onChange={this.handleChange} />
</p>
</div>
);
}
}
I forget to bind to bind fetchRecord() functions as per code below and issues solved
this.fetchRecord = this.fetchRecord.bind(this);
Related
I am new to angular and developing my very first application using angular 4 and typescript
I want to use Cascading drop-down in table using angular4
Currently, I have been working on it but when I change drop down from the first row it is a binding second level dropdown for all row.
I want to bind the second level drop down of the row from the first level drop down is changed.
I have some idea on my mind to achieve this but I guess It might be a patch so I am very curious to know any proper way of angular to achieve this.
ts file code
import { Component, OnInit, EventEmitter } from '#angular/core';
import { Category } from '../model/Category';
import { SubCategory } from '../model/subCategory';
import { Partner } from '../model/partner';
import { GetdataService } from '../../../../Server/api/Getdata.service';
import { Router } from '#angular/router';
#Component({
templateUrl: 'UploadFile.component.html'
})
export class UploadFileComponent implements OnInit {
AllCategoryList: Category[] = [];
AllSubCategoryList: SubCategory[] = [];
constructor(private _datatask: GetdataService, private _router: Router) { }
onChangeCategory(deviceValue) {
if (deviceValue > 0) {
this._datatask.getAllSubCategory(deviceValue).subscribe(
(data: SubCategory[]) => {
this.AllSubCategoryList = data;
}
);
console.log("from component: " + deviceValue);
}
else
{
//clear dropdown...
this.AllSubCategoryList= [];
}
}
ngOnInit() {
this._datatask.getAllCategory().subscribe(
(data: Category[]) => {
this.AllCategoryList = data;
}
);
this._datatask.getAllPartner().subscribe(
(data: Partner[]) => {
this.AllPartnerList = data;
}
);
}
}
HTML file
<div>
<table width="100%" border="1">
<thead>
<th>Category</th>
<th>SubCategory</th>
<th>Partner</th>
</thead>
<tbody *ngFor="let transaction of transactions">
<tr>
<td>
<select style="Width:100px;" (change)="onChangeCategory($event.target.value)" >
<option value=0>--Select--</option>
<option value="{{item.ID}}" *ngFor="let item of AllCategoryList" [ngValue]="item.ID" >{{item.Category}}</option>
</select>
</td>
<td>
<select style="Width:100px;">
<option value=0>--Select--</option>
<option *ngFor="let item of AllSubCategoryList" [ngValue]="item.ID" >{{item.SubCategory}}</option>
</select>
</td>
<td>
<select style="Width:100px;">
<option value=0>--Select--</option>
<option *ngFor="let item of AllPartnerList" [ngValue]="item.ID" >{{item.PartnerName}}</option>
</select>
</td>
</tr>
</tbody>
</table>
</div>
any help will be highly appreciated.
The problem is you needed an array of states... (in the plunker you listed in the comments below).
You can probably apply same to your code in original question.
list-component.ts tweaks
export class CountryListComponent {
states: State[] = [[] as State[],[] as State[],[] as State[]]
onSelect(value,index) {
this.states[index] = this._dataService.getStates().
filter((item)=> item.countryid == value);
}
}
list-component.html tweak
Updated: after this exchange with #GünterZöchbauer :
Use (ngModelChange) over (change)
<select [(ngModel)]="selectedCountry[number].id"
(ngModelChange)="onSelect($event, number)">
Fixed Plunker
I am also faced this problem and finally got a solution using custom pipe.
make a filter in external file like - mycustomfilter.ts
mycustomfilter.ts
import { Pipe, PipeTransform } from '#angular/core';
#Pipe({
name: 'myCustomFilter',
pure: false
})
export class myCustomFilterPipe implements PipeTransform {
transform(items: any[], field : string, value): any[] {
if (!items) return [];
if (!value || value.length === 0) return items;
return items.filter(it =>
it[field] === value);
}
}
declarations in app module
#NgModule({
imports: [ BrowserModule, FormsModule ],
declarations: [ App, myCustomFilterPipe],
bootstrap: [ App ]
})
item-order.component.ts
categoryList=[{id:1,name:'Office Stationery'},
{id:2,name:'Grocery'}
];
itemList=[
{id:1,name:'Pen',categoryID:1},
{id:2,name:'A4 Peper',categoryID:1},
{id:3,name:'Oil',categoryID:2},
{id:4,name:'Sugar',categoryID:2}
];
item-order.component.html
<tr *ngFor="let order of o.controls; let i = index" [formGroup]="order" class="form-row">
<td>
<select class="form-control" formControlName="ItemCategoryID">
<option value="">Select</option>
<option *ngFor="let s of categoryList" [ngValue]="s.id">{{s.name}}</option>
</select>
</td>
<td>
<select class="form-control" formControlName="ItemID">
<option value="">Select</option>
<option *ngFor="let s of itemList | myCustomFilter : 'categoryID' : order.value.ItemCategoryID" [ngValue]="s.id">{{s.name}}</option>
</select>
</td>
</tr>
Hi Im trying to list the items selected from the drop-down box and display it in a table using angularjs.So here is the code,
https://plnkr.co/edit/8qCgB2flMGB89moppkz6?p=preview
abc.html
Car Brand:
<select name="carname" ng-model="userSelect" required>
<option value="">--Select--</option>
<span ng-show="valdate.carname.$error.required">Car name</span>
<option ng-repeat="ManufactureBrand in a" ng-bind="ManufactureBrand" >
{{ManufactureBrand}}
</option>
</select>
<br/>
<br/> Car Model:
<select name="carmodel" ng-model="selectCar" required>
<option value="">--Select--</option>
<span ng-show="valdate.carmodel.$error.required">Car name</span>
<option ng-repeat="CarName in b" ng-bind="CarName">
{{CarName}}
</option>
</select>
<br/>
<input type="submit" ng-click="checkselection()" ng-disabled="valdate.carname.$invalid && valdate.carmodel.$invalid">
<table>
<tr>
<th>Car Name</th>
<th>Car Model</th></tr>
<tr>
<td>{{list}}</td>
<td>{{carlist}}</td>
</tr>
</table>
abc.js
var app = angular.module('carService', []);
app.factory('Brandtest', function () {
var brand = {};
brand.sample = ['Bmw', 'Mercedes', 'Honda'];
brand.car = ['Suv', 'Sedan', 'Cope'];
{
return brand;
}
});
app.controller('selectDropdown', ['$scope', 'Brandtest', function ($scope, Brandtest) {
$scope.a = Brandtest.sample;
$scope.b = Brandtest.car;
$scope.list=[];
$scope.carlist=[];
$scope.checkselection = function () {
if ($scope.userSelect != "" && $scope.userSelect != undefined &&
$scope.selectCar != "" && $scope.selectCar != undefined )
{
$scope.list.push($scope.userSelect);
$scope.carlist.push($scope.selectCar);
}
I have also attached image, how my final result is displayed.
here all the items in list once submitted are overlapping in the same row.
So, please help me to properly display the table and also on submitting the selected item from drop down I want them to be one below the other.
please check this working plunkr
The following are the code modified
<table>
<tr>
<th>Car Name</th>
<th>Car Model</th></tr>
<tr ng-repeat="carz in list track by $index">
<td>{{carz}}</td>
<td>{{carlist[$index]}}</td>
</tr>
</table>
I'm an angular newbie and am working on a small project and have come across a weird problem with ng-controller. When I use the controller within my partial view, the customer's name does not get passed into the value property.
However, if I inject the customersFactory (which has a function that makes an http request to the database to get all customers) into the ordersController, everything works fine.
My routeProvider code:
myApp.config(function($routeProvider) {
$routeProvider
.when('/', {
controller: 'ordersController',
templateUrl: 'partials/orders.html'
})
.when('/customers', {
controller: 'customersController',
templateUrl: 'partials/customers.html'
})
.otherwise({
redirectTo: '/'
})
});
myApp.factory('ordersFactory', function($http) {
var orders = [];
var factory = {};
factory.getOrders = function(callback) {
$http.get('/orders').success(function(data) {
orders = data;
callback(orders);
})
}
factory.addOrder = function(data) {
return $http.post('/add/order', data);
}
factory.deleteOrder = function(id) {
return $http.delete('/delete/order/' + id);
}
return factory;
});
myApp.factory('customersFactory', function($http) {
var customers = [];
var factory = {};
factory.getCustomers = function(callback) {
$http.get('/customers').success(function(data) {
customers = data;
callback(customers);
})
}
factory.addCustomer = function(data) {
return $http.post('/add/customer', data);
}
factory.removeCustomer = function(customer_id) {
return $http.delete('/delete/customer/' + customer_id);
}
return factory;
});
myApp.controller('ordersController', function($scope, ordersFactory) {
var getOrders = function() {
ordersFactory.getOrders(function(data) {
$scope.orders = data;
});
}
getOrders();
$scope.addOrder = function() {
console.log($scope.order);
ordersFactory.addOrder($scope.order);
$scope.order = {};
getOrders();
}
$scope.deleteOrder = function(id) {
ordersFactory.deleteOrder(id);
getOrders();
}
});
myApp.controller('customersController', function($scope, customersFactory) {
var getCustomers = function() {
customersFactory.getCustomers(function(data) {
$scope.customers = data;
})
}
getCustomers();
$scope.addCustomer = function() {
customersFactory.addCustomer($scope.customer);
$scope.customer = {};
getCustomers();
}
$scope.removeCustomer = function(customer_id) {
customersFactory.removeCustomer(customer_id);
getCustomers();
}
});
Here's the orders.html partial page.
<h2>Add New Order</h2>
<form>
<label for="name">Customer</label>
<select name="name" ng-model="order.name" ng-controller="customersController">
<option ng-repeat="customer in customers" value="{{customer.name}}">{{ customer.name }}</option>
</select>
<label for="quantity">Order</label>
<select name="quantity" ng-model="order.quantity">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<select name="product" ng-model="order.product">
<option value="Nike Shoes">Nike Shoes</option>
<option value="Black Belts">Black Belts</option>
<option value="Ice Creams">Ice Creams</option>
<option value="Candies">Candies</option>
<option value="Waffles">Waffles</option>
</select>
<input type="submit" value="Order" ng-click="addOrder()">
</form>
<table>
<thead>
<tr>
<td>Customer Name</td>
<td>Product</td>
<td>Quantity</td>
<td>Date</td>
<td>Action</td>
</tr>
</thead>
<tbody>
<tr ng-repeat="order in orders">
<td>{{ order.name }}</td>
<td>{{ order.product }}</td>
<td>{{ order.quantity }}</td>
<td>{{ order.date }}</td>
<td>Remove</td>
</tr>
</tbody>
</table>
Can anyone please explain why this is the case? My initial guess is that it has something to do with not explicitly assigning $scope.customers but I am under the impression that as soon as ng-controller is detected, it executes all of the "self-executing functions" which would then assign the data to $scope.customers. Thanks in advance.
Use ng-model in place of value and instead of <option> tag use ng-options in select tag it is fast as compare the <option> tag
<select name="name" ng-model="order.name" ng-controller="ordersController" ng-options="customer as customer in customers" />
Use the ngOptions directive instead. The documentation can be found here: https://docs.angularjs.org/api/ng/directive/ngOptions
<select name="name" ng-model="order.name" ng-options="customer as customer.name for customer in customers track by customer.name" ng-controller="ordersController">
Try ng-model="customer.name" instead of value="{{customer.name}}"
Thanks so much for your feedback. I think I've figured out the root of my issue(s).
I am not using ng-options to iterate over an array full of objects.
I am calling the ordersController in the routeProvider but am overriding it with customersController which is causing ng-model="order.name" to not be passed into the scope.
Any pointers on what I can do to fix #2? Does "ng-controller='customersController' have to come before the tag in order for "ng-options" to display the options correctly?
I have this URL working with my site using wp-api -
http://scd.blaze.wpengine.com/wp-json/posts?type=listings&filter[listing_area]=midlands
which outputs this code (using a chrome plugin to display it neatly) -
I'm really new to this and would appreciate if someone could point me in the right direction of how to use AngularJS (This is what I've read is best to use) to display this data on a useable page.
This is the code I have so far pulling in the data -
<script type="text/javascript">
function goToNewPage()
{
var url = document.getElementById('list').value;
if(url != 'none') {
window.location = url;
}
}
</script>
<select name="list" id="list" accesskey="target">
<option value='none' selected>Choose a region</option>
<option value="http://scd.blaze.wpengine.com/wp-json/posts?type=listings&filter[listing_area]=northwest">North West</option>
<option value="http://scd.blaze.wpengine.com/wp-json/posts?type=listings&filter[listing_area]=northeast">North East</option>
<option value="http://scd.blaze.wpengine.com/wp-json/posts?type=listings&filter[listing_area]=midlands">Midlands</option>
<option value="http://scd.blaze.wpengine.com/wp-json/posts?type=listings&filter[listing_area]=eastanglia">East Anglia</option>
<option value="http://scd.blaze.wpengine.com/wp-json/posts?type=listings&filter[listing_area]=southeast">South East</option>
<option value="http://scd.blaze.wpengine.com/wp-json/posts?type=listings&filter[listing_area]=southwest">South West</option>
<option value="http://scd.blaze.wpengine.com/wp-json/posts?type=listings&filter[listing_area]=scotland">Scotland</option>
<option value="http://scd.blaze.wpengine.com/wp-json/posts?type=listings&filter[listing_area]=wales">Wales</option>
<option value="http://scd.blaze.wpengine.com/wp-json/posts?type=listings&filter[listing_area]=northernireland">Northern Ireland</option>
<option value="http://scd.blaze.wpengine.com/wp-json/posts?type=listings&filter[listing_area]=channel">Channel Islands</option>
<select>
<input type=button value="Go" onclick="goToNewPage()" />
The link - http://scd.blaze.wpengine.com/test/
Thanks for any help in advance!
Ok there is not much Angular in your code but here is a starting point:
View:
<div ng-app="myApp" ng-controller="regionsCtrl">
<label>Select a region:</label>
<select ng-options="region for region in regions" ng-model="region" ng-change="getRegionData()">
</select>
<table>
<tr>
<th>id</th>
<th>Title</th>
<th>Status</th>
<th>Type</th>
</tr>
<tr ng-repeat="d in data">
<td>{{d.ID}}</td>
<td>{{d.title}}</td>
<td>{{d.status}}</td>
<td>{{d.type}}</td>
</tr>
</table>
</div>
Controller:
var app = angular.module('myApp', []);
app.controller('regionsCtrl', function($scope, $http) {
$scope.regions = [
'North West', 'North East', 'Midlands', 'East Anglia', 'South East', 'South West', 'Scotalnd', 'Wales'
]
$scope.getRegionData = function() {
var region = $scope.region
$http.get("http://scd.blaze.wpengine.com/wp-json/posts?type=listings&filter[listing_area]=#{region}").then(function(data) {
$scope.data = data; //this is the data that server returns
})
}
});
take a look at this fiddle
What this does is makes an call to the server using the region from the select menu, then stores the array returned from server in a variable on the scope (data in this case), then you can iterate over it in your view using ng-repeat.
Bear in mind that I can't access the server due to cors but if you have the right credentials it should work.
I'm new to angular, I was trying to display cascading dropdown lists. Here is my html code
<div class="row" ng-controller="createCabsTicketController as tktCreatecabsCntrl">
<select id="LocalCompanyIDForSearch" ng-change="getIXs()" ng-model="createCabsTicket.cabsCompanies.selected" name="LocalCompanyIDForSearch" class="form-control" style="width:100%;">
<option value=" "> </option>
<option ng-repeat="localCompany in createCabsTicket.cabsCompanies"
value="{{ localCompany.CompanyID }}">
{{ localCompany.LongDescription }}
</option>
</select>
<select id="IXCname" name="IXCname" class="form-control" style="width:100%;">
<option value=" "> </option>
<option ng-repeat="ix in createCabsTicket.IXCarrierNames"
value="{{ ix.Interexchange }}">
{{ ix.Interexchange }}
</option>
</select>
And here is my js file contents
app.controller('createCabsTicketController',['$scope','$http',function($scope,$http){
$scope.createCabsTicket = {
cabsCompanies: [],
IXCarrierNames: [],
IXCarrierIds:[]
};
$http.get('http://localhost:52377/api/reference/companies/active', { cache: true }).success(function (data) {
$scope.createCabsTicket.cabsCompanies = data;
});
$scope.getIXs = function (selectedItem) {
var postData = { ActiveOnly: true, CompanyId: selectedItem, CarrierId: "", CarrierName: "", CarrierType: "" };
$http.post('http://localhost:52377/api/reference/interexchanges', postData, { cache: true }).success(function (data) {
$scope.createCabsTicket.IXCarrierNames = data;
});
}
}]);
The web services work and the parent list gets populated just fine. But the ng-change event doesn't get fired. I am not sure what did I do wrong. I have found similar posts but they were not quite helpful to solve my problem. Please help!!