Set default value for dropdownlist using angularjs? - javascript

I have code that populates then dropdownlist and the javascript variable that gets the last item in the list. Now all I want to do is select that last item as the default .What am I missing ?
<div class="row">
<div>
<select ng-init="lastItem" ng-model="congressFilter" ng-options="cc.congressLongName for cc in ccList"></select>
</div>
<div class="grid-style" data-ng-grid="userGrid">
</div>
ccResource.query(function (data) {
$scope.ccList.length = 0;
angular.forEach(data, function (ccData) {
$scope.ccList.push(ccData);
})
//Set default value for dropdownlist?
$scope.lastItem = $scope.ccList[$scope.ccList.length - 1];
});

You simply need to asign a value to congressFilter in your controller.
$scope.congressFilter = 'someVal';
It depends a little on how your data looks however.

It might help to new developers. need to add default id for display default item in option.
The below code sample we add [ $scope.country.stateid = "4" ] in controller $scope to set the default.
var aap = angular.module("myApp", []);
aap.controller("MyContl", function($scope) {
$scope.country = {};
$scope.country.stateid = "4";
$scope.country.states = [{
id: "1",
name: "UP"
}, {
id: "4",
name: "Delhi"
}];
});
<body ng-app="myApp">
<div ng-controller="MyContl">
<div>
<select ng-model="country.stateid" ng-options="st.id as st.name for st in country.states">
</select>
ID : {{country.stateid}}
</div>
</div>
</body>

Related

Angularjs: Transfer data from <select> to lists

In angular, how would I change this selection to a list while maintaining the same functionality and data?
<select ng-if="main.fbWriteup.data"
name="selectGroup"
class="form-control"
ng-model="main.selectedGroup"
ng-options="key as key for (key,group) in main.fbWriteup.data"
ng-change="main.selectedMessage=-1">
</select><br/>
here is my full code: http://codepen.io/Zancrash/pen/KVYdqP/
You can add a group and the groups added are displayed within the dropdown menu. But I want all of them to be shown as a list item instead.
OK, I think I know what you're looking for.
I've created a new demo fiddle because your code is hard to read.
Just use ng-repeat to loop over your list of groups and add ng-click for selecting the group.
Please have a look at the demo below or in this fiddle.
angular.module('demoApp', [])
.controller('mainController', MainController);
function MainController($scope) {
var vm = this,
defaultEntries = [{
id: 0,
name: 'group1'
},{
id: 1,
name: 'group2'
}];
angular.extend(vm, {
groups: defaultEntries,
selectedGroup: defaultEntries[0],
addGroup: function() {
var newGroupName = prompt('enter group name'),
newItem = {id: vm.groups.length+1, name: newGroupName}
vm.groups.push(newItem);
vm.selectedGroup = newItem; // select new item
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="demoApp" ng-controller="mainController as ctrl">
<button ng-click="ctrl.addGroup()">
Add Group
</button>
<select ng-model="ctrl.selectedGroup" ng-options="group as group.name for group in ctrl.groups"></select>
group selected: {{ctrl.selectedGroup}}
<h1>
Group list
</h1>
<ul>
<li ng-repeat="group in ctrl.groups">{{group.name}}</li>
</ul>
</div>

Angular dynamic selects have items that affect one another

I'm attempting to make a dynamic form in Angular 1.4.7 in which:
There are multiple reports (vm.reports = [];)
Each report can be assigned ONE report object via vm.reportOptions.
Each vm.reportOptions can only be selected ONCE across multiple reports, which is filtered via exclude.
Each report supports MANY dimension objects via vm.dimensionOptions.
Each dimension can only be selected ONCE per report, which is filtered via excludeDimensions (subsequent reports have access to all the dimensionOptions and filter on their own).
These requirements are all working (roughly) with the exception of:
If I add two reports, and add the exact same dimensions (ie: Report One > Dimension One > Enable Dimension Filter and Report Two > Dimension One > Enable Dimension Filter) for each of the reports, changing the select inside of Enable Dimensions Filter changes it in both the reports.
I assume that this is happening due to the fact that I'm pushing the actual dimension objects in to each reports dimensions: [] array and that they are still pointing to the same object.
-- EDITS --
I realize angular.clone() is a good way to break this reference, but the <select> code I wrote is automatically piping in the object to the model. I was tempted to give each report their own controller and giving each report their own copy() of the options.
Would this work? Or is there a better way?
I have a working JSBin here.
Pertinent Code:
HTML:
<body ng-app="app">
<div ng-controller="AlertsController as alerts">
<pre>{{alerts.output(alerts.reports)}}</pre>
<div class="container">
<div
ng-repeat="report in alerts.reports"
class="report"
>
<button
ng-if="$index !== 0"
ng-click="alerts.removeItem(alerts.reports,report)"
>Delete Report</button>
<label>Select Report</label>
<select
ng-model="alerts.reports[$index].report"
ng-init="report"
ng-options="reportSelect.niceName for reportSelect in alerts.reportOptions | exclude:'report':alerts.reports:report"
></select>
<div
ng-repeat="dimension in report.dimensions"
class="condition"
>
<div class="select">
<h1 ng-if="$index === 0">IF</h1>
<h1 ng-if="$index !== 0">AND</h1>
<select
ng-model="report.dimensions[$index]"
ng-change="alerts.checkThing(report.dimensions,dimension)"
ng-init="dimension"
ng-options="dimensionOption.niceName for dimensionOption in alerts.dimensionOptions | excludeDimensions:report.dimensions:dimension"
>
<option value="123">Select Option</option>
</select>
<button
class="delete"
ng-if="$index !== 0"
ng-click="alerts.removeItem(report.dimensions,dimension)"
>Delete</button>
</div>
<input type="checkbox" ng-model="dimension.filtered" id="filter-{{$index}}">
<label class="filter-label" for="filter-{{$index}}">Enable Dimension Filter</label>
<div ng-if="dimension.filtered">
<select
ng-model="dimension.operator"
ng-options="operator for operator in alerts.operatorOptions">
</select>
<input
ng-model="dimension.filterValue"
placeholder="Text"
></input>
</div>
</div>
<button
ng-click="alerts.addDimension(report)"
ng-if="report.dimensions.length < alerts.dimensionOptions.length"
>Add dimension</button>
</div>
<button
ng-if="alerts.reports.length < alerts.reportOptions.length"
ng-click="alerts.addReport()"
>Add report</button>
<!--
<div ng-repeat="sel in alerts.select">
<select ng-model="alerts.select[$index]" ng-init="sel"
ng-options="thing.name for thing in alerts.things | exclude:alerts.select:sel"></select>
</div>
-->
</div><!-- container -->
</div>
</body>
JS:
var app = angular.module('app', []);
app.controller('AlertsController', function(){
var vm = this;
vm.reportOptions = [
{id: 1, niceName: 'Report One'},
{id: 2, niceName: 'Report Two'},
{id: 3, niceName: 'Report Three'},
];
vm.dimensionOptions = [
{id: 1, niceName: 'Dimension One'},
{id: 2, niceName: 'Dimension Two'},
{id: 3, niceName: 'Dimension Three'},
];
vm.operatorOptions = [
'>',
'>=',
'<',
'<=',
'=',
'!='
];
////// DEBUG STUFF //////
vm.output = function(value) {
return JSON.stringify(value, undefined, 4);
}
////////////////////////
vm.reports = [];
vm.addReport = function() {
vm.reports.push({report: {id: null}, dimensions: []});
}
vm.removeItem = function(array,item) {
if(array && item) {
var index = array.indexOf(item);
if(index > -1) {
array.splice(index,1);
}
}
}
vm.addDimension = function(report) {
console.log('addDimension',report);
if(report) {
report.dimensions.push({})
}
};
// init
if(vm.reports.length === 0) {
vm.reports.push({report: {}, dimensions: [{}]});
// vm.reports.push({report: vm.reportOptions[0], dimensions: [vm.dimensionOptions[0]]});
}
});
app.filter('excludeDimensions', [function() {
return function(input,select,selection) {
// console.log('ed',input,select,selection);
var newInput = [];
for(var i = 0; i < input.length; i++){
var addToArray=true;
for(var j=0;j<select.length;j++){
if(select[j].id===input[i].id){
addToArray=false;
}
}
if(addToArray || input[i].id === selection.id){
newInput.push(input[i]);
}
}
return newInput;
}
}]);
app.filter('exclude', [function () {
return function(input,type,select,selection){
var newInput = [];
for(var i = 0; i < input.length; i++){
var addToArray=true;
for(var j=0;j<select.length;j++){
if(select[j][type].id===input[i].id){
addToArray=false;
}
}
if(addToArray || input[i].id === selection[type].id){
newInput.push(input[i]);
}
}
return newInput;
};
}]);
How do I get around pushing same object reference to array
Use angular.copy()
array.push(angular.copy(vm.formObject));
// clear object to use again in form
vm.formObject={};
I ended up using select as so that it just set an id on the object instead of pointing to the original object. This solved the problem.

How to show item from json Array one by one in Angular JS

I am developing one prototype application in ionic framework. I am newbie for angular js, HTML, CSS , Java Script and all this stuff.
I have one json file which I am using as an input. I am able to parse this Json file and able to get json object from this. This json object contains array of items. You can refer below json content for this. Here items are application A,B.....
Updated Input Json :
{
"data": [
{
"applicationname": "A",
"permissions": [
{
"text": "at"
},
{
"text": "at1"
}
]
},
{
"applicationname": "B",
"permissions": [
{
"text": "bt"
},
{
"text": "bt1"
}
]
}
]
}
When the application loads for the first time, application should load only the first item from above json array which means only application "A" (first item) data.
Once user clicks on any button (install/cancel) in Footer then it should changed its data and display application "B"'s contents. This process should continue till the end of json array.
My current code is not loading even the first item data in. Am I doing something wrong in HTML?
Updated Code :
HTML file :
<ion-header-bar class="bar-calm">
<h1 class="title">Application Permissions</h1>
</ion-header-bar>
<ion-nav-view name="home" ng-repeat="app in applicationdata">
<div class="bar bar-subheader bar-positive">
<h3 class="title"> {{app.applicationname }}</h3>
</div>
<ion-content class="has-subheader">
<div class="list" ng-controller="CheckboxController">
<ion-checkbox ng-repeat="item in app.permissions" ng-model="item.checked" ng-checked="selection.indexOf(item) > -1" ng-click="toggleSelection(item)">
{{ item.text }}
<h3 class="item-text-wrap"> details come soon </h3>
</ion-checkbox>
<div class="item">
<pre ng-bind="selection | json"></pre>
</div>
<div class="item">
<pre ng-bind="selection1 | json"></pre>
</div>
</div>
</ion-content>
<ion-footer-bar align-title="left" class="bar-light" ng-controller="FooterController">
<div class="buttons">
<button class="button button-balanced" ng-click="infunc()"> Install </button>
</div>
<h1 class="title"> </h1>
<div class="buttons" ng-click="doSomething()">
<button class="button button-balanced"> Cancel </button>
</div>
</ion-footer-bar>
</ion-nav-view>
app.js file :
pmApp.controller('CheckboxController', function ($scope, $http, DataService) {
// define the function that does the ajax call
getmydata = function () {
return $http.get("js/sample.json")
.success(function (data) {
$scope.applicationdata = data;
});
}
// do the ajax call
getmydata().success(function (data) {
// stuff is now in our scope, I can alert it
$scope.data = $scope.applicationdata.data;
$scope.devList = $scope.data[0].permissions;
console.log("data : " + JSON.stringify($scope.data));
console.log("first application data : " + JSON.stringify($scope.devList));
});
$scope.selection = [];
$scope.selection1 = [];
// toggle selection for a given employee by name
$scope.toggleSelection = function toggleSelection(item) {
var idx = $scope.selection.indexOf(item);
var jsonO = angular.copy(item);
jsonO.timestamp = Date.now();
DataService.addTrackedData(jsonO);
$scope.selection1 = DataService.getTrackedData();
// is currently selected
if (idx > -1) {
$scope.selection.splice(idx, 1);
}
// is newly selected
else {
DataService.addSelectedData(item);
$scope.selection = DataService.getSelectedData();
/* $scope.selection.push(item);*/
}
};
});
Problems :
1 : Why is the data of first item not getting loaded? I have done changes in HTML as per my understanding.
2 : How Can I navigate through all items. I will try #John Carpenter's answer. Before that first problem should be resolved.
Please help me, thanks in advance.
OK, so I'm not 100% sure what you want but I'll take a stab at it. In the future, it would be helpful to post less code (probably not the entire project you are working on). It is a good idea to make a simpler example than the "real" one, where you can learn what you need to learn and then go apply it to the "real" code that you have.
Anyways, this example is a simple button that you click on to change what is displayed.
var app = angular.module('MyApplication',[]);
app.controller('MyController', ['$scope', function($scope){
$scope.indexToShow = 0;
$scope.items = [
'item 1',
'item 2',
'item 3'
];
$scope.change = function(){
$scope.indexToShow = ($scope.indexToShow + 1) % $scope.items.length;
};
}]);
.simple-button {
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="MyApplication" ng-controller="MyController">
<div ng-repeat="item in items track by $index" ng-show="$index == indexToShow">
{{item}}
</div>
<div class="simple-button" ng-click="change()">click me!</div>
</div>

i10n angularjs assign translate variable

Okay so i have the following small translation file:
{
"components" : {
"1" : "Video",
"2" : "Lyd",
"3" : "Dokument",
"4" : "Tekst"
}
}
And then i have the following li item:
<li ng-repeat="type in componentTypes" ng-hide="module.module_type_id == 2 || module.module_type_id == 10">{{type.name}}</li>
What you need to notice is :
{{type.name}}
Or more precisely:
translate="components.{{1}}"
With this it does not translate the <a></a> tag.
However if i do
translate="components.1"
it translates correctly however this method doesnt work for me
so my question is how can dynamicly change the value of a the translate attribute?
The reason components.{{1}} is not working is because the double curlies in Angular is just meant to evaluate an expression. 1 is just a number, so you'll get components.1 everytime.
If I understand what you need correctly, you need to have a corresponding component based on type. So if type.id === 1 then your type is Video.
In order to achieve that in Angular dynamically, you should just have:
translate="{{components[type.id]}}"
Fiddle
As far as I understand you want to dynamize the translation json if added a new type to your componentTypes array.
There is a solution for that need, you can implement a new custom translation loader factory and use it with specified way here https://github.com/angular-translate/angular-translate/wiki/Asynchronous-loading. After that you have to add this new item to the translation json, your array and then refresh the translation.
View:
<div ng-app="myApp">
Links to jsfiddle.net must be accompanied by code. Please indent all code by 4 <div ng-controller="MyCtrl">
<input type="text" ng-model="type.name" /> Add Component
<ul>
<li ng-repeat="type in componentTypes" ng-hide="module.module_type_id == 2 || module.module_type_id == 10">{{ 'components.' + type.name | translate }}</li>
</ul>
</div>
</div>
Implementation of your application:
var myApp = angular.module('myApp', ['pascalprecht.translate']);
var components_en = {
"components": {
"1": "Video",
"2": "Lyd",
"3": "Dokument",
"4": "Tekst"
}
};
myApp.config(function ($translateProvider) {
$translateProvider.useLoader('customLoader', {});
$translateProvider.translations('en', components_en);
$translateProvider.preferredLanguage('en');
});
myApp.controller('MyCtrl', function ($scope, $translate) {
$scope.module = {
module_type_id: 1
};
$scope.addComponent = function (type) {
// Add the componentTypes array you took from database
$scope.componentTypes.push({
name: $scope.componentTypes.length + 1
});
// Add the translation object
components_en["components"][$scope.componentTypes.length] = type.name;
console.log(components_en);
$translate.refresh();
};
$scope.componentTypes = [{
name: 1
}, {
name: 2
}, {
name: 3
}, {
name: 4
}];
});
myApp.factory('customLoader', function ($http, $q) {
return function (options) {
var deferred = $q.defer();
deferred.resolve(components_en);
return deferred.promise;
}
})
I prepared a demonstration for that like usage, please below jsfiddle:
http://jsfiddle.net/nerezo/1z071wzg/6/
Note: This like translation modifications will not be persistent and new translations will be lost.
Please give this a try:
translate="{{'components.' + type.id}}" //if there is id in type
or
translate="{{'components.' + ($index + 1)}}"

Process a value before displaying it with AngularJS

I have a controller that update a value according to a radiobuttons list.
MyTypes = {
"cat": 0,
"dog": 1,
"cow": 2
};
function MyController($scope) {
$scope.value= 1; //Updated by a radiobuttons list
}
<!-- Display -->
<label >Type ({{value}})</label>
This would display "1". I would like to display "dog". Is there a way to call a function inside the html template? This function would find the key associated to value.
I've been doing it like this:
[snip MyTypes setup]
function MyController($scope) {
var typesById = [];
angular.forEach(MyTypes,function(v,k){typesById[+k]=v;});
$scope.typesById=typesById;
$scope.value= 1; //Updated by a radiobuttons list
}
<!-- Display -->
<label >Type ({{typesById[value]}})</label>

Categories