I have 2 DropDowns in MVC and trying to use AngularJS. My first DropDown gets filled with data that comes from the DB properly. When the user makes a selection on the first DropDown, the second DropDown should be filled according to the selection. But, it doesnt get triggered. What am I doing wrong?
When I select from the first DropDown, Chrome Console show this error "undefined". But, it is defined, why does it show this error?
here is my html code...
<form name="mainForm" ng-controller="PriceListEditController" novalidate>
<div class="error">{{message}}</div>
<select id="brandSelect" ng-model="brandSelect" ng-options="b.Id as b.Name for b in brands" ng-change="GetBrandPriceList()">
<option value="">Marka Seçiniz</option>
<option ng-repeat="b.Id for b in brands" value="{{b.Id}}">{{b.Name}}</option>
</select>
<select ng-model="priceList" ng-options="b.Id as b.Name for b in priceLists">
<option value="">-- Select Country --</option>
<option ng-repeat="p.Id for p in priceLists" value="{{p.Id}}">{{p.Name}}</option>
</select>
</form>
here is my JS code...
var app = angular.module('PriceListEditModule', []);
app.controller('PriceListEditController', ["$scope", "$q", "$http", function ($scope, $q, $http) {
$http({
method: 'GET',
url: '/GetBrands'
}).then(function successCallback(response) {
$scope.brands = response.data;
}, function errorCallback(response) {
$scope.message = 'Unexpected Error ' + response.message;
});
$scope.GetBrandPriceList = function () {
console.log($scope.brandSelect);
var brandId = $scope.brandSelect;
if (brandId>0) {
$http({
method: 'GET',
url: '/GetBrandPriceList'
}).then(function successCallback(response) {
$scope.priceLists = response.data;
}, function errorCallback(response) {
$scope.message = 'Unexpected Error ' + response.message;
});
}
else {
$scope.priceList = null;
}
}
}]);
You use ng-options and ng-repeat in the same select section.
Try this in you html:
<form name="mainForm" ng-controller="PriceListEditController" novalidate>
<div class="error">{{message}}</div>
<select id="brandSelect" ng-model="brandSelect" ng-change="GetBrandPriceList()">
<option value="">Marka Seçiniz</option>
<option ng-repeat="b in brands" value="{{b.Id}}">{{b.Name}}</option>
</select>
test
<select ng-model="priceList">
<option value="">-- Select Country --</option>
<option ng-repeat="p in priceLists" value="{{p.Id}}">{{p.Name}}</option>
</select>
</form>
Related
I use select2, $localStorage and angularjs in my project, I want to get the value of my $localstorage as a default value but when I try this
$('.select').val($localStorage.f.tab.idSelect).trigger('change');
it doesn't work it doesn't show my default value I have the same issue for my select multiple
$('.selectSec').val($localStorage.f.tab.selectSecArray).trigger('change');
this is my .aspx file
<select class="form-control select">
<option value="">---Please select---</option>
<option ng-repeat="option in test" value="{{option.testid}}">{{option.testname}}</option>
</select>
<select class="form-control selectSec" name="secs[]" multiple="multiple">
<option value="">---Please select---</option>
<option ng-repeat="option in secs" value="{{option.secid}}">{{option.secname}}</option>
</select>
this is my app.js
app.controller('AppCtrl', function ($scope, $http, $localStorage) {
$http.get("url1").then(function (response) {
$scope.test= response.data.Liste
})
$http.get("url2").then(function (response) {
$scope.secs= response.data.Liste
})
$('.select').val($localStorage.f.tab.idSelect).trigger('change');
$('.selectSec').val($localStorage.f.tab.selectSecArray).trigger('change');
jQuery(".select").change(function (e) {
if (e.target.value == "")
console.log("null")
else
$localStorage.f.tab.idSelect = e.target.value
}) // I do the same for the multiple select
})
When do that it doesn't work but if I add this opt in my .select
Test nb 20
and I do this
$localStorage.f.tab.idSelect = 20
$('.select').val($localStorage.f.tab.idSelect).trigger('change');
It works perfectly so how can I make my select2 works with my angularjs and my $localstorage
The ng-repeat show default empty string for first option. Why in may case it does not work. What is wrong in here?
My angular code is here. What i mistake here. I don't understand.
var exchange = angular.module('app', []);
exchange.controller('ExchangeController', ExchangeController);
function ExchangeController($scope, $http) {
$http
.get(window.location.origin + "/api/get-item/", {
transformRequest: angular.identity,
headers: {'Content-Type': undefined, 'Process-Data': false}
})
.then(function(response){
$scope.items = response.data.items;
$scope.send_item_id = $scope.items[0].value;
});
$scope.getSendItem = function() {
var send_item_id = $("#send_item_id").val();
console.log(send_item_id);
}
}
Here is my html code,
<div class="form-group">
<div class="col-md-12 col-sm-12">
<select data-plugin-selectTwo
name="send_item_id"
id="send_item_id"
ng-model="send_item_id"
ng-change="getSendItem()"
class="form-control populate">
<option ng-repeat="item in items" value="#{{ item.value }}">#{{ item.text }}</option>
</select>
</div>
</div>
You need to manually select a "selected" item (itemSelected model in my solution) and change your value attribute to ng-value to make it work in the AngularJS way. Please check this demo fiddle I've created for you. Btw. you don't need jQuery here: please check how I log the selected item in getSendItem(). This will work for AngularJS 1.6.x or later.
View
<div ng-controller="MyCtrl">
<select data-plugin-selectTwo
name="send_item_id"
id="send_item_id"
ng-model="itemSelected"
ng-change="getSendItem()"
class="form-control populate">
<option ng-repeat="item in data" ng-value="item.value">
#{{ item.text }}
</option>
</select>
</div>
AngularJS application
var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', function($scope) {
$scope.data = [{
"text": "Bkash",
"value": 1
}, {
"text": "Paypal",
"value": 2
}];
$scope.itemSelected = $scope.data[0].value;
$scope.getSendItem = function() {
console.log($scope.itemSelected);
}
});
While using AngularJS 1.5.x or earlier you need to do it like in this demo fiddle by using ng-selected:
View
<div ng-controller="Controller">
<select name="send_item_id"
id="send_item_id"
ng-model="itemSelected"
ng-change="getSendItem()">
<option
ng-repeat="item in data" value="{{ item.value }}"
ng-selected="{{item.value === itemSelected}}">
{{ item.text }}
</option>
</select>
</div>
AngularJS application
var myApp = angular.module('app', []);
myApp.controller('Controller', function($scope) {
$scope.data = [{
"text": "Bkash",
"value": 1
}, {
"text": "Paypal",
"value": 2
}];
$scope.itemSelected = String($scope.data[0].value);
console.log($scope.itemSelected);
$scope.getSendItem = function() {
console.log($scope.itemSelected);
}
You need to match the option value and ng-model value in order to prevent the default empty space. in your case it does not match since there is # symbol in front of your option value. remove it.
<option ng-repeat="item in items" value="{{ item.value }}">#{{ item.text }}</option>
Try this. It's working for me.
<option value="{{item.value}}" ng-repeat="item in items" ng-selected="$first">{{ item.text }}</option>
I'm trying to implement the classic Country > State > City combobox using angular directives.
I'm willing to link them by a custom attribute pair name/depends-on, but I don't know if there's a better form.
My HTML is the following:
<div ng-app="app" ng-controller="Ctrl">
<multiselect source-url="/countries.json" auto-init="true" name="Contries">
<select multiple ng-model="$parent.selectedOptions" ng-change="$parent.handleChange()">
<optgroup ng-repeat="(continent, countries) in $parent.optionList" label="{{continent}}">
<option ng-repeat="country in countries" value="{{country.code}}">
{{country.code}} - {{country.name}}
</option>
</optgroup>
</select>
</multiselect>
<multiselect source-url="/states.json" depends-on="Countries" name="States">
<select multiple ng-model="$parent.selectedOptions" ng-change="$parent.handleChange()">
<optgroup ng-repeat="(continent, countries) in $parent.optionList" label="{{continent}}">
<option ng-repeat="country in countries" value="{{country.code}}"> {{country.code}} - {{country.name}}
</option>
</optgroup>
</select>
</multiselect>
</div>
The Javascript:
app.directive('multiselect', function () {
return {
restrict: 'E',
transclude: true,
scope: {
sourceUrl : '#',
autoInit : '#',
dependsOn : '#'
},
controller: ['$scope', '$element', '$attrs', '$transclude', '$http', function ($scope, $element, $attrs, $transclude, $http) {
$scope.handleChange = function handleChange() {
console.log($scope.selectedOptions)
}
console.log($scope.dependsOn)
function updateSource() {
const config = {
params : {}
}
if ($scope.dependsOn) {
// how do I get dependsOnValue?????
config.params[$scope.dependsOn.toLowerCase()] = $scope.dependsOnValue
}
$http.get($scope.sourceUrl, config)
.then(function (response) {
$scope.optionList = response.data
})
}
if ($scope.autoInit) {
updateSource()
}
}],
template: '<ng-transclude></ng-transclude>'
}
})
The question is: how do I watch for changes in Countries in order to get its value to update States?
I'm trying to make this as reusable as possible.
I am populating a select dropdown menu by making a call to an api. When the user chooses an option from the select menu I wish to fire the second function - $scope.getRoles(). However, this is firing immediately. Any ideas why this is happening? Please see my attempted code below.
html
<select>
<option ng-change="getRoles()" ng-repeat="country in countries">{{ country.countryCode }}</option>
</select>
angular
app.controller("jobsCtrl", function($scope, careerData) {
//get list of countries when app loads
careerData.countryList().then(function successCallback(response) {
$scope.countries = response.data;
$scope.countries.unshift({countryCode: "Select a country"});
}, function errorCallback(response) {
console.log(response);
});
$scope.getRoles = careerData.jobByCountry().then(function successCallback(response) {
console.log(response)
}, function errorCallback(response) {
console.log(response);
})
});
app.factory('careerData', ['$http', function($http){
return {
countryList: function() {
return $http({
method: 'GET',
url: 'testUrl'
})
},
jobByCountry: function() {
return $http({
method: 'GET',
url: 'someurl'
})
}
}
}]);
First you should use ngOptions.
Change this:
<select>
<option ng-change="getRoles()" ng-repeat="country in countries">{{ country.countryCode }}</option>
</select>
for:
<select ng-options="country as country.countryCode for country in countries" ng-model="countrySelected" ng-change="getRoles()">
</select>
Example:
angular.module('app', [])
.controller('mainCtrl', function($scope) {
$scope.cars = ["Audi", "BMW", "Corolla", "Mercedes"];
$scope.check = function() {
console.log($scope.car);
}
});
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script>
</head>
<body ng-controller="mainCtrl">
Cars:
<select ng-model="car" ng-options="car for car in cars" ng-change="check()">
<option value="">Select a car</option>
</select>
</body>
</html>
so I think you were looking for this
(ngModelChange)="getRoles()"
in your HTML tag.
this will fire when you change the module it works for most input field I came across here because it doesn't work with mat-select.
this is for angular 7. this is also an old question.
comment:
but I hope this will help you because this is still not answered if the previous answer works accept it.
I've created a directive for a select input to select a userId. The model binds from the directive to the rest of the view. However, when I set the id from the controller it doesn't seem to bind to select input in the directive.
Controller:
app.controller('MainCtrl', function($scope) {
// set userId to willem's Id
$scope.userId = 3;
});
Directive:
app.directive('selectUser', function() {
return {
restrict: 'E',
scope: {
ngModel: '='
},
controller: function($scope) {
$scope.users = [{
"id": 1,
"name": 'Tupac'
}, {
"id": 2,
"name": 'Biggie'
}, {
"id": 3,
"name": 'Willem'
}];
},
templateUrl: 'directive.html'
};
});
index.html
<body ng-controller="MainCtrl">
users:
<select-user ng-model="userId"></select-user>
userId = {{userId}}
</body>
directive.html
<select class='form-control focus' ng-model="ngModel">
<option value="">all users</option>
// doesn't bind from the controller. Supposed to show willem, instead of all users to start with.
<option ng-Repeat="user in users" value="{{user.id}}">{{user.name}}</option>
</select>
Working example on: http://plnkr.co/edit/c7eyoB
You should use ngOptions :
<select class='form-control focus' ng-model="ngModel" ng-options="user.id as user.name for user in users">
<option value="">all users</option>
</select>
Then the binding will work. See updated plnkr
Edit, concerning the following question in comment :
could you please explain, why it is not working with ng-repeat?
You can achieve the same visual result with :
<select class='form-control focus' ng-model="ngModel">
<option value="">all users</option>
<option ng-repeat="user in users" value="{{user.id}}" ng-selected="user.id === ngModel">{{user.name}}</option>
</select>
I.e. we added ng-selected="user.id === ngModel".
But this has some drawbacks. First, you are creating unneeded isolated scopes. And also, the values bound to the options are strings, i.e. you will actually select '1', '2' or '3' instead of 1, 2 or 3.