How to reload nested state of different controller when changing selectbox content in AngularJS?
I have 2 select boxes 1.Category and 2.SubCategory
Based on the category and subcategory, Products will be displayed on the inner state
category and subcategory come under addproducts state
products come under .productsettings state inside the addproducts state
But my problem is when I select both category and subcategory the product will be displayed that means
$state.go('addproducts.productsettings');
will work,But after selecting both after that when i change only subcategory selectbox it won't reload product state
$state.go('addproducts.productsettings');
will not work that wont load in ProductSettingsController
This is my html code it contains two select boxes
<form>
<div class="form-group">
<label for="exampleSelect1"><b>Category</b></label>
<select ng-model="selectedCategory" class="form-control" id="categories" ng-init="selectedCategory = null"
ng-change="onCategoryChange(selectedCategory)">
<option value="">--Select--</option>
<option ng-repeat="(key,value) in categories | orderBy:'catName'| groupBy:'catName'">{{key}}</option>
</select>
</div>
</form>
<!-- ----------------------------------- -->
</div>
<div class="col-md-3">
<!-- ----------------------------------- -->
<form>
<div class="form-group">
<label for="exampleSelect1"><b>SubCategory</b></label>
<select class="form-control" id="subcategories" ng-model="selectedSubCategory" ng-disabled="!selectedCategory"
ng-options="categories.subCatName for categories in categories | filter: {catName:selectedCategory}" ng-change="getValue()">
<option value="">--Select--</option>
</select>
</div>
</form>
<!-- ----------------------------------- -->
</div>
This is my js code
var appshop = angular.module('appShop', [ 'ui.router', 'angular.filter' ]);
appshop.config(function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/category');
$stateProvider.state('addproducts',
{
url : '/addproducts',
views :
{
'body' :
{
templateUrl : 'category/manageproduct.htm',
controller : 'AddProductController'
}
}
})
.state('addproducts.productsettings',
{
url : '/productsettings',
views :
{
'productsbody#addproducts' :
{
templateUrl : 'category/productsettings.htm',
controller : 'ProductsSettingsController'
}
}
})
});
//==========================================================
appshop.controller('AddProductController',AddProductController);
function AddProductController($scope, $http,$state)
{
$scope.onCategoryChange = function(category)
{
if (!category)
{
$scope.selectedSubCategory = undefined;
}
}
var categoryPromise = $http.get("../rest/mcategory");
categoryPromise.success(function(data, status, headers, config)
{
$scope.categories=data;
});
categoryPromise.error(function(data, status, headers, config)
{
alert("Error");
});
$scope.getValue=function()
{
$state.go('addproducts.productsettings');
}
}
//==========================================================
appshop.controller('ProductSettingsController',ProductSettingsController);
function ProductSettingsController($scope,$http,$state)
{
alert("Clicked")//I need to get alert here
}
That two select boxes are come under AddProductController
And products are comed under nested state of this AddProductController it is named as ProductSettingsController
When i select both category and subcategory it works fine
But after selcting both then only to changed subcategory it wont works
Any idea for getting product details when i select subcatname? I need to get alert Clicked in ProductSettingsController when i changed in subcategory selectbox
use $stateParams means parameters in url: look
HTML SubCategory section
<!-- ----------------------------------- -->
<form>
<div class="form-group">
<label for="exampleSelect1"><b>SubCategory</b></label>
<select class="form-control" id="subcategories" ng-model="selectedSubCategory" ng-disabled="!selectedCategory"
ng-options="categories.subCatName for categories in categories | filter: {catName:selectedCategory}" ng-change="getValue(selectedSubCategory)">
<option value="">--Select--</option>
</select>
</div>
</form>
<!-- ----------------------------------- -->
JS add stateParams in substate
.state('addproducts.productsettings',
{
url : '/productsettings?:subitem',
views :
{
'productsbody#addproducts' :
{
templateUrl : 'category/productsettings.htm',
controller : 'ProductsSettingsController'
}
}
})
Controller
$scope.getValue=function(sub_item)
{
$state.go('addproducts.productsettings', {subitem:sub_item});
}
try:
$state.reload();
or
$state.go('addproducts.productsettings', {}, {reload: true});
Related
there is a dropdown of country and state when I select country of name I have to pass id of country but after click event it should pass id but display as name how can I make it please guide
<md-select name="state" id="state" placeholder="Select a state" md-no-asterisk="true"
ng-change="getCounties(state)" ng-model="state">
<md-option ng-repeat="item in state track by id"
value="{{item.id}}">
{{item.name}}
</md-option>
</md-select>
{{AddressState}} /* This should be name instead of value how can i display this ? */
<div class="clearfix" ng-click="edit()">
Edit</a></div>
controller.ts :
$scope.AddressState = state;
Don't use state as your ng-model since state is already your data source. Consider instead using an object to capture all user input, with state as a property. Your ng-model will capture the ID on user selection, which is what you want, and you can use that to get the state name.
angular.module('myApp', [])
.controller('myCtrl', ['$scope', function($scope) {
$scope.userInput = {
state: {}
};
$scope.state = [{
"name": "Califoria",
"id": 1
}, {
"name": "Texas",
"id": 2
}]
$scope.getCounties = function() {
// $scope.userInput.state is updated autmatically with the ID
console.log($scope.userInput)
// the associated data can be found using
let state = $scope.state.find(s => s.id == $scope.userInput.state)
$scope.selectedState = state.name; // for display
}
}]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<select ng-model="userInput.state" ng-change="getCounties()">
<option ng-repeat="item in state" value="{{item.id}}">
{{item.name}}
</option>
</select>
<p> {{selectedState}} </p>
</div>
country names displaying using select box, select option coming from external json file. Based on selected country i am loading state json file into another select box,till every thing is ok, Now I need set Default selected country as INDIA, I tried bellow code.
html
<div ng-app="myApp" ng-controller="myCtrl">
<div>
<select id="country" ng-init="state1 = options['IN']" style="width:250px;" class="" name="selectFranchise" ng-model="state1" ng-change="displayState(state1)">
<option ng-repeat="(key,country) in countries" value="{{key}}">{{country[0]}}</option>
</select>
</div>{{countries}}{{state1}}
<div>
<select id="state" ng-model="cities">
<option ng-repeat="(state,city) in states[state1]" value="{{city}}">{{city}}</option>
</select>
</div>
</div>
script
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.states = {
"IN":[
"Delhi",
"Goa",
"Gujarat",
"Himachal Pradesh",
]
};
$scope.countries = {
IN: ["India"],
ZA: ["South Africa"],
AT: ["Austria"]
}
$scope.lastName = "Doe";
});
jsfiddle
Add this in the controller after defining your $scope.countries
$scope.state1 = Object.keys($scope.countries)[0];
Remove ng-init from Html page.
I mixed EJS and AngularJS in a webapp, but now I'm having problems to load a default value for a dropdown (select element).
I use the same HTML file to add and update users.
I have a URL that return all values loaded in the dropdown, accessed in the Angular controller when the page loads.
This is the controller:
angular.module('app').controller('userCtrl', function($scope, $http) {
...
function getCities() {
$http.get('/rest/cities').then(function(response) {
vm.cities = response.data.records;
});
}
The EJS sends the default value via response (as in this example):
router.get('/user', function(req, res) {
res.render('pages/user', { defatultCity: 10 });
}
The HTML builds the dropdown with this code:
<select id="city" name="city" class="form-control input-sm" required>
<option></option>
<option ng-repeat="x in cities" value="{{x.idCidade}}"> {{ x.Nome }} </option>
</select>
What I have 'unsuccessfully' tried so far (in the HTML):
To validate value from Angular with value from EJS
<option ng-repeat="x in cities" value="{{x.idCity}}" <%if (defaultCity == %> {{x.idCity}} <%) {%> selected <%}%> > {{ x.Nome }} </option>
To insert a hidden input to hold the value in the HTML and inside the controller I added a JQuery
<input type="hidden" id="defaultCity" value"<%=defaultCity%>" />
// In the controller (it return an error - this.each is not a function)
$('city').val($('#defaultCity'))
I know these attempts are ugly, but I could not find a way to make it work yet. I'll be happy if someone knows how to do it.
PS: I would like to avoid passing all the city list of values from NodeJS to use EJS forEach command inside the HTML.
Thank you!
Add this piece of code at the end of your .ejs template
<script type="text/javascript">
angular.module('app')
.value('myCity', <%- JSON.stringify(defaultCity) %>);
</script>
then inject the component in your controller:
app.controller('myCtrl', function ($scope, myCity) {
function getCities() {
$http.get('/rest/cities').then(function(response) {
vm.cities = response.data.records;
// myCity must be an object - same as vm.cities[0], for example
$scope.defaultCity = myCity;
});
});
and change your HTML file to have the default value
<select ng-model="defaultCity"
ng-options="city as city.name for city in cities track by city.id"
id="city" name="city" class="form-control input-sm" required >
<option></option>
</select>
Demo:
I have a dropdown, and options are being fecthed from JSON.
say
<select ng-model="projectModel" ng-options="project as project.projectName">
<option>one</option>
<option>two</option>
<option>three</option>
<option>four</option>
<option>and so on... </option>
</select>
i have two views page1.html and page2.html
in page1.html i have the following code.
select box with above options when ever user select an option say, user has selected three. this has to be saved somewhere. i dont where to save, so next when user clicks page2.html the data selected before in page1.html should not reset.
HTML :
<body ng-app="staticSelect">
<div ng-controller="ddController">
<form name="myForm">
<label for="singleSelect"> Single select: </label><br>
<select name="singleSelect" ng-model="data.singleSelect">
<option ng-repeat="x in options">{{x}}</option>
</select><br>
<tt>singleSelect = {{data.singleSelect}}</tt>
</form>
</div>
</body>
JS
app.controller('ddController', ['$scope', function($scope) {
$scope.data = {
singleSelect: null,
};
$scope.options = ["red","blue","yellow"];
}]);
app.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: '01.html',
controller: 'htmlCtrl',
})
.when('/html', {
templateUrl: '02.html',
controller: 'htmlCtrl',
})
})
any help would be much appreciated!
Thanks
Added a reference for 'ng-cookies' in the main view and a service to set and get a cookie.
In Html:
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular-cookies.js"></script>
The binding html has the method to set the cookie through ng-change
<select name="singleSelect" ng-model="data.singleSelect" ng-change="setSelect()">
<option ng-repeat="x in options">{{x}}</option>
</select>
You can see the CookieService in the Working Demo
In Controller:
When the setSelect() method is fired the selected value is set in cookie, when the view is returned back to it will re store the value from the cookie
if(cookieService.getAppData("selected") !== null && cookieService.getAppData("selected") !== undefined){
$scope.data.singleSelect = cookieService.getAppData("selected");
}
$scope.setSelect = function (){
cookieService.setAppData("selected", $scope.data.singleSelect);
}
Need to Filter options in dropdown based on manufacturers (make). Need to filter models based on selected make option via "ng-model:make"
HTML:
<div class="form-group">
<label for="make">Make</label>
<select class="form-control" data-ng-model="make" data-ng-options="maker.make for maker in makers" required></select>
</div>
<div class="form-group">
<label for="make">Make</label>
<select class="form-control" data-ng-model="make" data-ng-options="maker.make for maker in makers" required></select>
</div>
<div class="form-group">
<label for="model">Model</label>
<select class="form-control" data-ng-model="model" data-ng-options="availabledevice.model for availabledevice in availabledevices|filter:make" required></select>
</div>
Services from factory:
deviceassign.factory("manufacturersoptionsservice", function($http) {
var devicemakers = {};
devicemakers.values = function() {
return $http.get('api/displaymanufacturersapi.php');
}
return devicemakers;
});
deviceassign.factory("availabledeviceservice", function($http) {
var availabledevice = {};
availabledevice.details = function() {
return $http.get('api/displayavailabledevicesforoptionsapi.php');
}
return availabledevice;
});
Controller:
deviceassign.controller('assigndevicecontroller', function($scope, growl, manufacturersoptionsservice, availabledeviceservice) {
manufacturersoptionsservice.values().success(function(response1) {
$scope.makers = response1;
});
availabledeviceservice.details().success(function(response3) {
$scope.availabledevices = response3;
});
// ...
});
Its working now.Had to select make.make as make itself is an object in JSON
<select class="form-control" data-ng-model="model" data-ng-options="availabledevice.model for availabledevice in availabledevices|filter:make.make" required></select>