AngularJS - ng-options not populating the list of objects - javascript

Am trying to populate combo box in AngularJS. Below is the controller code.
var app = angular.module('app');
app.controller('roadmap', function($rootScope, $scope, $http, $q, leFactory) {
$rootScope.activityInfoList=[];
$rootScope.brand_strategy_list=[];
$rootScope.brand_strategy_csf=[];
$rootScope.brand_strategy_initiatives=[];
leFactory.getActivityPopupInfo().then(function(activityList) {
$rootScope.activityInfoList=angular.copy(activityList);
console.log($rootScope.activityInfoList);
$rootScope.brand_strategy_list=$rootScope.activityInfoList.listBrandStrategy;
console.log($rootScope.brand_strategy_list);
console.log('editActivityPopup service accepted-> ');
}, function(error) {
console.log('editActivityPopup service rejected-> ', error);
});
$rootScope.items = [{
id: 1,
label: 'aLabel',
subItem: { name: 'aSubItem' }
}, {
id: 2,
label: 'bLabel',
subItem: { name: 'bSubItem' }
}];
});
In the HTML part, am trying to populate $rootScope.brand_strategy_list as below.
<select ng-model="activityInfoList.brandStrategy" class="selectpicker" data-style="btn-inverse" style="display: none;" ng-options="item.strategyName as item.strategyName for item in brand_strategy_list">
<option> Select </option>
</select>
$rootScope.brand_strategy_list is not getting populated. But when I tried populating $rootScope.items, it is getting populated. I made console.log($rootScope.brand_strategy_list) and its showing the complete list.
Dont know what mistake am doing? Pls help me solve this issue. Thanks in Advance.

Try this
ng-options="item.strategyName as item.strategyName for item in $root.brand_strategy_list

Remove style="display: none;" from html and change $rootScope to $scope
<select ng-model="activityInfoList.brandStrategy" class="selectpicker" data-style="btn-inverse" ng-options="item.strategyName as item.strategyName for item in brand_strategy_list">
<option> Select </option>
</select>

Related

angular js ng-option not working for select tag

I'm trying to get the ng-option to use a JSON formatted array, but not sure why it's not displaying the select option rows. For instance:
index.js:
$scope.seloptions= [{ key: k1, name: n1 },{ key: k2, name: n2 }];
index.html:
<select name="set_aside" ng-model="set_aside" ng-options="option.key for option in seloptions track by name"></select>
I have no idea what I'm doing wrong. The select tag is not getting populated.
EDIT
Also assume that the necessary setup for the angular code is there and both files are in same directory.
The problem is that you are tracking by name which is undefined.
update line :
ng-options="option.key for option in seloptions track by name"
to
ng-options="option.key for option in seloptions track by option.name"
Working example :
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.seloptions= [{ key: "key1", name: "n1" },{ key:" key2", name: "n2" }];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="plunker">
<div ng-controller="MainCtrl">
<select name="set_aside" ng-model="set_aside" ng-options="option.key for option in seloptions track by option.name">
<option value="">Select One</option>
</select>
</div>
</body>

AngularJS Select | After selecting an id from a JSON show the rest of the information of that id

I have a JSON saved that has plenty information:
I am able to fill a select menu with all the names of each element inside the JSON this way:
<select ng-model="car.marca" ng-options="item.brakeId as item.name for item in fillBreaks" class="form-control cforms" required>
<option value="" disabled selected>Sleccionar Marca</option>
</select>
Getting this as result: a select menu filled with the names:
I am able to get the BreakId of the selected element, in this case is saved in 'car.marca' using ng-model.
ng-model="car.marca"
My question is, Based on the selected element lets say 'BrakeId: 9' how can I display the rest of the information of that selected id?
I want to display the price, description, stock, and so on.
You can get the selected object by doing a find on fillBreaks (should be fillBrakes?) for an object with a matching brakeId using ng-change like below. This will allow you to display the additional brake information while keeping car.marca true to holding just a brakeID.
var exampleApp = angular.module('exampleApp', []);
exampleApp.controller('ExampleController', ['$scope', function($scope) {
$scope.car = null;
$scope.fillBreaks = [
{ brakeId: 0, name: 'Brake A', description: 'Good brakes', price: 100, stock: 1 },
{ brakeId: 1, name: 'Brake B', description: 'Great brakes', price: 200, stock: 1 },
{ brakeId: 2, name: 'Brake C', description: 'The best brakes', price: 300, stock: 1 }
];
$scope.brakeInfo = null;
$scope.getBrakeInfo = function(brakeId) {
$scope.brakeInfo = $scope.fillBreaks.find(function(item){return item.brakeId == brakeId});
}
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="exampleApp" ng-controller="ExampleController">
<select ng-model="car.marca" ng-options="item.brakeId as item.name for item in fillBreaks" ng-change="getBrakeInfo(car.marca)" class="form-control cforms" required>
<option value="" disabled selected>Sleccionar Marca</option>
</select>
<p>{{ brakeInfo }}</p>
</div>
You can change your ng-options to grab the entire selected object, instead of just it's ID.
ng-options="item as item.name for item in ctrl.fillBreaks"
See this JSFiddle for example
P.S. A little trick to remove the Placeholder option from the dropdown is to add style="display: none;" to it, so that it can't be intentionally selected; also illustrated in the JSfiddle

Dropdown menus in AngularJS

I have two dropdown menus in my angular app. When I select an option in the 1st dropdown menu, I want that choice to effect the 2nd dropdown menu. Example: 1st menu will have a list of status messages. When I select, let's say, "Need Maintenance" It will change the 2nd menu to the departments relevant to the Maintenance. Or if I choose the status "Lost", it will change the 2nd menu to the departments relevant to the Lost status. Here is my code and setup:
.controller('HomeCtrl', function($scope, $rootScope, $http, $ionicPlatform) {
// This disables the user from being able to go back to the previous view
$ionicPlatform.registerBackButtonAction(function (event) {
event.preventDefault();
}, 100);
// This function only gets called when the submit button is hit on the messaging screen. It posts to server for sending of message
$scope.submit = function() {
$http.post('http://localhost:8000/', {
messageText: $scope.messageText,
name: window.localStorage.getItem("username")
});
$scope.messageText = ""; //clearing the message box
}
})
<div class="form1" ng-controller="HomeCtrl">
<form class="form">
<select placeholder="Select a Subject" ng-model="selectSubject" data-ng-options="option.subject for option in subject"></select>
<select placeholder="Select a Department" ng-model="selectDept" data-ng-options="option.dept for option in dept"></select>
<input type="text" class="messageText" placeholder="Message" ng-model="messageText">
<button class="button" ng-click="submit()"><span>Submit</span></button>
</form>
</div>
That is my controller relevant to the html that is also posted.
I know how to get the information I need from my node server which will be housing the information. All I need help figuring out is changing the options within the 2nd menu when a option is clicked in the 1st menu.
I am thinking just having a http.get call when a option is clicked which will then populate the 2nd menu. The first menu will be static, not changing.
I've just started messing around with Angular and a database and and was able to dynamically populate one select based on the choice in another.
Below is the HTML for my two select boxes (my second select is a multiple, but you can obviously remove that attribute):
<label>Select a Table</label>
<select name="tableDropDown" id="tableDropDown"
ng-options="table.name for table in data.availableTables"
ng-model="data.selectedTable"
ng-change="getTableColumns()">
</select>
<label>Select Columns</label>
<select name="columnMultiple" id="columnMultiple"
ng-options="column.name for column in data.availableColumns"
ng-model="data.selectedColumns"
multiple>
</select>
And I have the controller below. The init function clears all of the data sources for the two select's, retrieves the list of tables (for the first select), sets the selected table to the first table in the list, and then calls the second function.
The second function (which is also called whenever the selected table changes, thanks to the ng-change directive) retrieves the metadata for the selected table and uses it to populate the second select with the list of available columns.
.controller('SimpleController', function($scope, $http) {
init();
function init() {
$scope.data = {
availableTables: [],
availableColumns: [],
selectedTable: {}
};
$http.get("http://some.server.address")
.then(function (response) {
$scope.data.availableTables = response.data.value;
$scope.data.selectedTable = $scope.data.availableTables[0];
$scope.getTableColumns();
});
}
$scope.getTableColumns = function () {
$scope.data.selectedColumns = [];
table = $scope.data.selectedTable.url;
if (table != "") {
$http.get("http://some.server.address/" + table + "/$metadata?#json")
.then(function (response) {
$scope.data.availableColumns = response.data.value;
});
}
}
...
});
maybe you can use the ng-change directive on the 1st select and using the callback function to populate the 2nd select in the way you prefer( http call or local data).
if your Departments objects has a references to the Subject object, something like a subject_id, you can just do a filter:
Example:
<div ng-controller="MyCtrl">
subjects
<select placeholder="Select a Subject" ng-model="selectSubject" ng-options="subject.name for subject in subjects"></select>
departmets
<select placeholder="Select a Department" ng-model="selectDept" ng-options="dept.name for dept in depts | filter:{ subject_id : selectSubject.id }"></select>
</div>
var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {
$scope.subjects = [
{
id: 1,
name: "sub 1",
},
{
id: 2,
name: "sub 2",
}
];
$scope.depts = [
{
id: 1,
name: "Dep 1",
subject_id: 1
},
{
id: 2,
name: "Dep 2",
subject_id: 1
},
{
id: 3,
name: "Dep 3",
subject_id: 2
},
{
id: 4,
name: "Dep 4",
subject_id: 2
}
]
}

AngularJS option selected

I know there's been a lot of questions for this but I am having the most annoying time figuring out how AngularJS handles select option values and which one is selected. I have a simple item which I pass onto a modal window. This item contains template_id. I also have templates which have a name and an id and I wish to create a simple select where the option which has the value of the item's template_id gets selected:
<select name="templateId">
<option value="8000">name</option>
<option value="8001" selected>name 2</option>
</select>
Now with AngularJS I do this:
<select name="templateId"
ng-model="domain.templateId"
ng-options="t.template_id as t.name for t
in templates track by t.template_id">
<option value="">Choose template</option>
</select>
In the controller I set the 'selected' value with:
Data.get('templates').then(function(result) {
$scope.templates = result;
});
$scope.domain = {
template_id: item.template_id,
templateId: { template_id: item.template_id }
};
I have actually gotten to a point where I can send the template_id to the REST API and the response there reads
template_id: 8000
However, there is some minor annoying behaviour in the select element. I get the item I want selected, but when I attempt to select another option it switches the selected to the pre-set 'Choose template' option but the value or rather the 'real selected item' is still the original "selected" value I set in the controller. I can see it in the REST API response. This is not however what I selected. After this initial bug it continues to work as it's supposed to but how can I get rid of this?
Here a example to solve your issue.
angular.module('app.select', [])
.controller('SelecetCtrl', function($scope) {
$scope.templates = [{
template_id: 1,
name: 'tst1'
}, {
template_id: 2,
name: 'tst2'
}, {
template_id: 3,
name: 'tst3'
}];
$scope.selected = {
template: {
template_id: 2
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app='app.select'>
<div ng-controller='SelecetCtrl'>
<select name="templateId" ng-model="selected.template"
ng-options="t as t.name for t
in templates track by t.template_id">
<option value="">Choose template</option>
</select>
</div>
</div>

Angularjs show selected option from ng-repeat value

I have drop down inside ng-repeat as follows.
<div ng-model="list in lists">
<div>
<select ng-model="pType" ng-options="c.name in projType"></select>
<option value="{{list.value}"></option>
</div>
My Controller is
App.controller('pOverCtrl', function ($scope, pOverRepository, $location) {
$scope.lists = projOverRepository.query();
$scope.projType = [
{ value: '0', name: 'None Selected' },
{ value: '1', name: 'Construction' },
{ value: '2', name: 'Maintenance' },
];
})
The dropdown gets populated fine. But my goal is that when ng-repeat is executed it automatically shows the value that is coming from lists scope as selected.
Please let me know how to fix this issue.
use the diretive ng-selected
<div ng-model="list in lists">
<select ng-model="pType" ng-options="c.name in projType">
<option ng-selected="list.value == list.selected" value="{{list.value}"></option>
</select>
</div>
assuming that list.selected variable contains the value of the option selects
$scope.pType should have the selected value as it's bind by ng-model.
Read the docs here: http://docs.angularjs.org/api/ng/directive/select
And if you already have the selected value in $scope.lists, you can use the ngSelected directive.

Categories